Can I modify data in a $scope from outside its controller?


#1

In my ionic newbie adventures, I’ve come across a new obstacle:
I need to build the app’s main list from a sqlite database, so when the app loads, I need to read the table and populate my list (I assume that the best way to do so is reading the objects from the db into an array and using a ng-repeat that pulls from it).

The sqlite part is not the problem (I’m using the CordovaSQLite-plugin and I’ve managed to learn the basics of it), but since from my research I should not run any sqlite calls before the device is ready, I need to populate the array from .run, within $ionicPlatform.ready.

So, I have:

.controller('Ctrl', function($scope, $cordovaSQLite)
{
    $scope.venues = [];
    ...
}

and

.run(function($ionicPlatform, $cordovaSQLite) 
{
    $ionicPlatform.ready(function() 
    {
        //I need to populate $scope.venues from here, apparently.
        ...
    }
}

in my html I have

<body ng-app="app" ng-controller="Ctrl">
    ...
    <ion-item ng-repeat="venue in venues">
        <div style="float:left">{{venue.name}}</div>
        <div style="float:right">{{venue.location}} - {{venue.type}}</div>
    </ion-item>
</body>

So that’s it, I don’t really know what to do from here to get the array populated.


#4

Sorry, but unless I’m missing something, I can’t see how that’s helpful. It’s apparently meant for debugging and mostly for reading (not writing) data. Also, it seems like it’s mostly to work with the DOM, not the underlying data.


#5

You could create a service and set the variable in that service. For example:

In controller:

.controller('Ctrl', function($scope, $cordovaSQLite, sharedData)
{
    $scope.sharedData = sharedData;
    ...
}

In run function:

.run(function($ionicPlatform, $cordovaSQLite, sharedData) 
{
    $ionicPlatform.ready(function() 
    {
        // populate sharedData.venues
        sharedData.venues = [];
        ...
    }
}

In html:

<body ng-app="app" ng-controller="Ctrl">
    ...
    <ion-item ng-repeat="venue in sharedData.venues">
        <div style="float:left">{{venue.name}}</div>
        <div style="float:right">{{venue.location}} - {{venue.type}}</div>
    </ion-item>
</body>

and then create the service like this:

.service('sharedData', function() {
    // Assign 'this' to a variable so we can reference sharedData
    // in functions
    sharedData = this;

    sharedData.venues = [];
});

I’m sure there are multiple ways of doing this but this is the way I pass data between my controllers and my ready function. I just typed this without testing it so there may be some things missing.


#6

And you can declare sharedData like :

.value(‘sharedData’, {});