$ look inside the service?

Is it possible to configure $watch in an array of objects inside the service (I would like the $watch declaration to be inside the service)?

+59
angularjs angularjs-service
Jul 23 '13 at 9:38 on
source share
3 answers

You can add any expression to the clock set by entering $rootScope and using the function, the first argument to the $watch method. Pseudo Code:

 $rootScope.$watch(function() { return //value to be watched; }, function watchCallback(newValue, oldValue) { //react on value change here }); 

Do not forget about the third, logical argument of the $watch method. You need to specify true if you want to deeply scan the entire object for changes.

+120
Jul 23 '13 at 9:52 on
source share
Services

by their very nature they are similar to classes and home methods. You can set up a method that you call on your controller, whose argument is the scope and applies the clock expression:

 app.service('myservice',function(){ this.listen = function($scope) { $scope.$watch(function(){return someScopeValue},function(){ //$scope.dosomestuff(); }); } }); //your controller function myCtrl($scope,myservice) { $scope.listen = function() { myservice.listen($scope); } //call your method $scope.listen(); } 

update: if you are trying to look at a private local variable inside the service, see the accepted answer using $ rootScope. If you are trying $ to look at the $ scope variable in the local scope, then this is the best option. They achieve two very different things.

+15
Mar 25 '14 at 1:13
source share

Can you clarify what you want to achieve? As far as I understand, you get an array of objects from the server as your model. Then this is not clear:

  • Do you want to check if some objects in the array have been changed (maybe since the last server call in case you are repeating Pools)?
  • Do you want to check if any objects in the array have been modified by the user through some foreground controls?

In case 1, you really do not need to use $ watch (or rather $ watchCollection), but you should iterate over the array received from the server and check for changes (the same as $ watchColleciton). If the object is different from the object that you are currently using, you call the object. $ Save () for this item.

In case 2, use $ watchCollection () in the $ scope passed as a parameter to your utility function, or use $ rootScope if you are holding your array in $ rootScope.

I can provide you real code if you clarify the scripts.

0
Mar 25 '14 at 1:51
source share



All Articles