Watching multiple values all at once in angularjs


We know how to watch a variable on the scope.

$scope.$watch('var1',function(newVal,oldVal){
 console.log(newVal);
  });











Say if we want to watch three variables inside our controller we have to have three watch blocks as shown

$scope.$watch('var1',function(newVal,oldVal){
 console.log(newVal);
  });

  $scope.$watch('var2',function(newVal,oldVal){
 console.log(newVal);
  });

  $scope.$watch('var3',function(newVal,oldVal){
 console.log(newVal);
  });

This will increase your number of lines of code and may become hard to manage if you have number of watch blocks.
Angular introduced $watchGroup in version 1.3 using which we can watch multiple variables, with a single $watchGroup block
$watchGroup takes array as first parameter in which we can include all of our variables to watch.


$scope.$watchGroup(['var1','var2','var3'],function(newVals,oldVals){
   console.log(newVals);
 });

Comments

  1. Infycle offers the solitary AWS Training in Chennai for the freshers, professionals, and students along with the additional course such as DevOps Training and Java training for making the candidate an all-rounder in the Software domain field. For a lucrative career, dial 7504633633.

    ReplyDelete

Post a Comment

Popular Posts