Thursday, May 3, 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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...