Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 601
Thilo Avatar asked Mar 30 '13 06:03

Thilo


2 Answers

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 :-)

like image 59
Golo Roden Avatar answered Nov 06 '22 02:11

Golo Roden


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

like image 39
Sten Muchow Avatar answered Nov 06 '22 04:11

Sten Muchow