Auto-updating scope variables in angularjs
angularjs, scope
Solution
UPDATE:
I made a demo plunker: http://plnkr.co/edit/dmu5ucEztpfFwsletrYW?p=preview I use `$timeout` to fake updates.
The trick is to use plain javascript references:
- You need to pass an object to the scope.
- You mustn't override that object, just update or extend it.
- If you do override it, you lose the "binding".
- If you use `$http` it will trigger a digest for you.
- So, whenever a change occurs, the scope variable reference to same object that gets updated in the service, and all the watchers will be notified with a digest.
- AFAIK, That's how `$firebase` & `Restangular` work.
- If you do multiple updates you need to have a way of resetting properties.
- Since you hold a reference to an object across the application, you need to be aware of memory leaks.
For example:
Service:
app.factory('inboxService', function($http){
return {
inboxForUser: function(user){
var inbox = {};
$http.get('/api/user/' + user).then(function(response){
angular.extend(inbox, response.data);
})
return inbox;
}
};
});
Controller:
app.controller('ctrl', function(inboxService){
$scope.inbox = inboxService.inboxForUser("fred");
});
Problem
I'm currently playing with AngularJS. I'd like to return, from a service, a variable that will let the scope know when it has changed. To illustrate this, have a look at the example from www.angularjs.org, "Wire up a backend". Roughly, we can see the following: ``` var projects = $firebase(new Firebase("http://projects.firebase.io")); $scope.projects = projects; ``` After this, all updates made to the `projects` object (through updates, be it locally or remotely) will be automatically reflected on the view that the scope is bound to. How can I achieve the same in my project? In my case, I want to return a "self-updating" variable from a service. ``` var inbox = inboxService.inboxForUser("fred"); $scope.inbox = inbox; ``` What mechanisms let the `$scope` know that it should update? EDIT: In response to the suggestions, I tried a basic example. My controller: ``` $scope.auto = { value: 0 }; setInterval(function () { $scope.auto.value += 1; console.log($scope.auto.value); }, 1000); ``` And, somewhere in my view: ``` <span>{{auto.value}}</span> ``` Still, it only displays 0. What am I doing wrong ?