$watch inside a service?

Kuba Orlik picture Kuba Orlik · Jul 23, 2013 · Viewed 29.9k times · Source

Is it possible to set up a $watch on an array of objects inside a service (I'd like the $watch declaration itself to be inside the service)?

Answer

pkozlowski.opensource picture pkozlowski.opensource · Jul 23, 2013

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.