Thursday, 3 May 2018

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:




{{ item }}





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?

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...