Understanding $watchGroup in AngularJS

Loading

$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 tracks firstName and lastName.
  • 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
TracksA single variable or expressionMultiple variables or expressionsProperties inside an object or array
Callback TriggerWhen the variable changesWhen any variable in the group changesWhen any property inside the object/array changes
Best ForWatching a single valueWatching multiple independent valuesWatching changes inside an object or array

Example:

ScenarioUse $watchUse $watchGroupUse $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().

Leave a Reply

Your email address will not be published. Required fields are marked *