Combining watchers with $watchGroup
You might find that multiple model components need to be tied to the same $watch
type callback. As of the 1.3 release, AngularJS provides the $watchGroup
method that accepts a collection of watch targets in which all the watch targets need to bind to the same callback.
How to do it…
The change event callback parameters can be an ordered array of the current values, followed by an ordered array of the previous values. This is shown here:
(app.js) angular.module('myApp',[]) .controller('Ctrl', function($scope, $log) { $scope.ping = 'pong'; $scope.ding = { dong: 'ditch' }; // watch ping and the ding.dong property by reference $scope.$watchGroup(['ping', 'ding.dong'], function(newVals, oldVals, scope) { // callback ...
Get AngularJS Web Application Development Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.