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



Comments

Post a Comment

Popular Posts