Return to site
· watch,Multiple variables,Angular JS,Webapplications,Web
broken image

To observe and react to changes in a value Angular.js has scope.$watch function. When you have to trigger events like callback etc on multiple objects using $watch you can use methods like $watchGroup and $watchCollection. Since Angular 1.3 Angular offers two scope methods $watchGroup and $watchCollection. An example of using $watchGroup is given below.

$scope.bar = 'bar';

  // newValues array contains the current values of the watch expressions

  // with the indexes matching those of the watchExpression array

  // i.e.

  // newValues[0] ->$scope.foo 

  // and 

  // newValues[1] ->$scope.bar 

});

$watchGroup method is a variant of $watch() where it watches array of watchExpressions and if any of those expressions in the collection changes the listener is executed. Through the standard $watch operation the items in the watchExpressions array are observed. Every call to $digest their return values are examined.

Example for watchCollection:

$scope.$watchCollection(['foo','bar'], function(newValues, oldValues){

    // do what you want here

});

$watchCollection shallow watches the properties of an object and fires whenever any of the property change. When the change is detected the listener callback is fired.