Thilo
Thilo

Reputation: 262474

How do I stop $watching in AngularJS?

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?

Upvotes: 77

Views: 32548

Answers (3)

Golo Roden
Golo Roden

Reputation: 150614

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();
});

Upvotes: 147

JOSEPH Blessingh
JOSEPH Blessingh

Reputation: 155

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!

Upvotes: 0

Sten Muchow
Sten Muchow

Reputation: 6701

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...

Upvotes: 22

Related Questions