AngularJS : Clear $watch
$watch
returns a deregistration function. Calling it would deregister the $watcher
.
var listener = $scope.$watch("quartz", function () {});
// ...
listener(); // Would clear the watch
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);
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!
}
}
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 () {});