[javascript] AngularJS : Clear $watch

I have a watch function in my AngularJS application.

$scope.$watch('quartzCrystal', function () {
   ...
}

However, after some condition (in my example, changing the page at my single-page application) I want to stop that watch (as like clearing timeout).

How can I do that?

This question is related to javascript angularjs watch

The answer is


If you have too much watchers and you need to clear all of them, you can push them into an array and destroy every $watch in a loop.

var watchers = [];
watchers.push( $scope.$watch('watch-xxx', function(newVal){
   //do something
}));    

for(var i = 0; i < watchers.length; ++i){
    if(typeof watchers[i] === 'function'){
        watchers[i]();
    }
}

watchers = [];

Some time your $watch is calling dynamically and it will create its instances so you have to call deregistration function before your $watch function

if(myWatchFun)
  myWatchFun(); // it will destroy your previous $watch if any exist
myWatchFun = $scope.$watch("abc", function () {});

You can also clear the watch inside the callback if you want to clear it right after something happens. That way your $watch will stay active until used.

Like so...

var clearWatch = $scope.$watch('quartzCrystal', function( crystal ){
  if( isQuartz( crystal )){
    // do something special and then stop watching!
    clearWatch();
  }else{
    // maybe do something special but keep watching!
  } 
}

Ideally, every custom watch should be removed when you leave the scope.

It helps in better memory management and better app performance.

// call to $watch will return a de-register function
var listener = $scope.$watch(someVariableToWatch, function(....));

$scope.$on('$destroy', function() {
    listener(); // call the de-register function on scope destroy
});

scope.$watch returns a function that you can call and that will unregister the watch.

Something like:

var unbindWatch = $scope.$watch("myvariable", function() {
    //...
});

setTimeout(function() {
    unbindWatch();
}, 1000);

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to angularjs

AngularJs directive not updating another directive's scope ERROR in Cannot find module 'node-sass' CORS: credentials mode is 'include' CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 Print Html template in Angular 2 (ng-print in Angular 2) $http.get(...).success is not a function Angular 1.6.0: "Possibly unhandled rejection" error Find object by its property in array of objects with AngularJS way Error: Cannot invoke an expression whose type lacks a call signature

Examples related to watch

What is the Angular equivalent to an AngularJS $watch? AngularJS $watch window resize inside directive Converting Milliseconds to Minutes and Seconds? AngularJS : Clear $watch How to deep watch an array in angularjs? AngularJS : How to watch service variables? OS X Bash, 'watch' command Is there a command like "watch" or "inotifywait" on the Mac? Watching variables in SSIS during debug How do I watch a file for changes?