Multi watch with $watchGroup in angular
We might want to stop watching a variable because we are not interested in it anymore once we are done with our operation. Angular provides a way to stop watching a variable. Certainly unwatching can increase performance.
To demonstrate this let me watch a variable on the scope.
$scope.$watch('var1',function(newVal,oldVal){
console.log(newVal);
});
The above code will be executed each time there is a change in the value of "var1". Once we are not interested in watching this variable anymore we can unwatch it.
To Unwatch, first grab the handle of watch. The $watch returns a handle as shown below
var unwatch= $scope.$watch('var1',function(newVal,oldVal){
console.log(newVal);
});
Inside my index.html i can have a button and click event. Once the button is clicked i want to stop watching.
<button ng-click="stop()">Stop Watching</button>
Then invoke the handle to stop watching the variable inside the click event of the button.
$scope.stop=function(){
unwatch();
}
The same trick can be applied to $watchGroup as well
var unwatch= $scope.$watchGroup(['var1','var2','var3',function(newVal,oldVal){
console.log(newVal);
});
$scope.stop=function(){
unwatch();
}
Great Blog .Feeling happy to read this useful post
ReplyDeleteMCSE Training in chennai | MCSE Course in chennai
Rpa training in chennai | RPA training course chennai
Existing without the answers to the difficulties you’ve sorted out through this guide is a critical case, as well as the kind which could have badly affected my entire career if I had not discovered your website.
ReplyDeleteBest PHP Training Institute in Chennai|PHP Course in chennai
Best .Net Training Institute in Chennai
Dotnet Training in Chennai
Dotnet Training in Chennai