$watch inside a service?
Solution 1:
You can add any expression to the set of watches by injecting the $rootScope
and using a function a 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
});
Don't forget about the third, Boolean argument to the $watch
method. You need to specify true
if you want to deep-watch an entire object for changes.
Solution 2:
services by their very nature are like classes and house methods. You can set up a method which you call from your controller who's argument is the scope and applies a watch 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 watch a private local variable inside of a service, see the accepted answer using $rootScope. If you are trying to $watch a $scope variable within a local scope than the above is your best bet. They are achieving two very different things.