Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS : How to watch service variables?

I have a service, say:

factory('aService', ['$rootScope', '$resource', function ($rootScope, $resource) {   var service = {     foo: []   };    return service; }]); 

And I would like to use foo to control a list that is rendered in HTML:

<div ng-controller="FooCtrl">   <div ng-repeat="item in foo">{{ item }}</div> </div> 

In order for the controller to detect when aService.foo is updated I have cobbled together this pattern where I add aService to the controller's $scope and then use $scope.$watch():

function FooCtrl($scope, aService) {                                                                                                                                 $scope.aService = aService;   $scope.foo = aService.foo;    $scope.$watch('aService.foo', function (newVal, oldVal, scope) {     if(newVal) {        scope.foo = newVal;     }   }); } 

This feels long-handed, and I've been repeating it in every controller that uses the service's variables. Is there a better way to accomplish watching shared variables?

like image 308
berto Avatar asked Sep 25 '12 05:09

berto


1 Answers

You can always use the good old observer pattern if you want to avoid the tyranny and overhead of $watch.

In the service:

factory('aService', function() {   var observerCallbacks = [];    //register an observer   this.registerObserverCallback = function(callback){     observerCallbacks.push(callback);   };    //call this when you know 'foo' has been changed   var notifyObservers = function(){     angular.forEach(observerCallbacks, function(callback){       callback();     });   };    //example of when you may want to notify observers   this.foo = someNgResource.query().$then(function(){     notifyObservers();   }); }); 

And in the controller:

function FooCtrl($scope, aService){   var updateFoo = function(){     $scope.foo = aService.foo;   };    aService.registerObserverCallback(updateFoo);   //service now in control of updating foo }; 
like image 126
dtheodor Avatar answered Oct 18 '22 08:10

dtheodor