$watchGroup
is an AngularJS scope method that allows watching multiple scope variables at once. It works like $watch
, but instead of tracking a single variable, it tracks an array of expressions and triggers a callback when any of them change.
Syntax
$scope.$watchGroup(['expression1', 'expression2', ...], function(newValues, oldValues) {
// Code to execute when any of the watched expressions change
});
- The first argument is an array of expressions (variables or functions).
- The second argument is a callback function that gets executed whenever any of the expressions change.
newValues
: An array containing the new values of the watched expressions.oldValues
: An array containing the previous values of the watched expressions.
Example: Watching Multiple Scope Variables
var app = angular.module("myApp", []);
app.controller("MainController", function ($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
$scope.$watchGroup(['firstName', 'lastName'], function (newValues, oldValues) {
console.log("Changes detected!");
console.log("New Values:", newValues);
console.log("Old Values:", oldValues);
});
// Simulate changes after 2 seconds
setTimeout(() => {
$scope.$apply(() => {
$scope.firstName = "Jane";
$scope.lastName = "Smith";
});
}, 2000);
});
Explanation:
- The
$watchGroup
tracksfirstName
andlastName
. - When either of them changes, the callback function runs.
- Inside
setTimeout()
,$scope.firstName
and$scope.lastName
are updated, triggering the$watchGroup
.
Comparing $watch
, $watchGroup
, and $watchCollection
Feature | $watch | $watchGroup | $watchCollection |
---|---|---|---|
Tracks | A single variable or expression | Multiple variables or expressions | Properties inside an object or array |
Callback Trigger | When the variable changes | When any variable in the group changes | When any property inside the object/array changes |
Best For | Watching a single value | Watching multiple independent values | Watching changes inside an object or array |
Example:
Scenario | Use $watch | Use $watchGroup | Use $watchCollection |
---|---|---|---|
Watching a single variable | Yes | No | No |
Watching multiple variables | No | Yes | No |
Watching an array/object’s properties | No | No | Yes |
Key Takeaways
✔ Use $watchGroup
when you need to monitor multiple independent variables at once.
✔ It improves performance over multiple $watch
calls.
✔ $watchGroup
does not detect deep changes inside objects (use $watchCollection
for that).
✔ Always use $scope.$apply()
when updating values inside async functions like setTimeout()
.