How do I stop $watching in AngularJS?

AngularjsAngularjs Scope

Angularjs Problem Overview


I can set up a $watch on an AngularJS scope to be notified when the expression I am interested in has changed. But how do I stop watching once I lose interest?

Angularjs Solutions


Solution 1 - Angularjs

When calling $watch a function is returned that unregisters the bound expression.

E.g., to watch a variable foo only change once:

var unregister = $scope.$watch('foo', function () {
  // Do something interesting here ...
  unregister();
});

Hope that helps :-)

Solution 2 - Angularjs

As an additional comment, but not answer - this is the same principle for killing event listeners as well.

var unregister = $rootScope.$on("listen-for-something-cool", function($event, params) {
   //Do cool stuff with params, then kill it
   unregister();
};

Just an addition I thought would be cool for anyone else to know...

Solution 3 - Angularjs

I am not sure how the accepted answer is working! For me it was not at all working.

I was using $watchCollection instead of $watch. I then tried to change it to $watch and applied the accepted answer but reached nowhere!!

The only thing which worked for me was:

var watchFoo = $scope.$watch('foo', function () {
  // Do something interesting here ...

    return;
});

return; was unregistering the watch and was breaking the watch Cycle. And it worked fine even after the cycle was broken. It was able to detect changes made on the Array.

My code looked something like:

var watchFoo = $scope.$watchCollection('foo', function (newFoo, oldFoo) {
    
     if(condition) {
         // Do something interesting here ...      
          return;
     } else {
         // Do something else here ...
     }
     
    });

The accepted answer can be used if it works out for you otherwise this answer will come in handy!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionThiloView Question on Stackoverflow
Solution 1 - AngularjsGolo RodenView Answer on Stackoverflow
Solution 2 - AngularjsSten MuchowView Answer on Stackoverflow
Solution 3 - AngularjsJOSEPH BlessinghView Answer on Stackoverflow