In AngularJS, $watchCollection()
is used to observe changes in an object or array’s properties. Unlike $watch()
, which tracks changes at the reference level, $watchCollection()
detects additions, deletions, and updates of elements in an array or object.
1. Syntax
$scope.$watchCollection(expression, listener);
- expression: The object or array to watch.
- listener: A function that executes when the watched collection changes.
2. Why Use $watchCollection()
?
Feature | $watch() | $watchCollection() |
---|---|---|
Detects reference changes | Yes | Yes |
Detects property value changes | No | Yes |
Detects additions/deletions in arrays | No | Yes |
Performance impact | High (Deep Watch) | Optimized |
3. Example: Tracking Array Changes
app.controller("MyController", function($scope) {
$scope.numbers = [1, 2, 3];
$scope.$watchCollection("numbers", function(newValue, oldValue) {
console.log("Array changed:", newValue);
});
// Modify array dynamically
$scope.addNumber = function() {
$scope.numbers.push(Math.floor(Math.random() * 10));
};
});
Detects new numbers added to the array.
4. Example: Tracking Object Property Changes
app.controller("MyController", function($scope) {
$scope.user = { name: "Alice", age: 25 };
$scope.$watchCollection("user", function(newValue, oldValue) {
console.log("User object changed:", newValue);
});
// Modify object properties
$scope.updateAge = function() {
$scope.user.age += 1;
};
});
Detects updates to user.age
, even though the object reference remains the same.
5. $watch()
vs $watchCollection()
in Objects
$scope.$watch("user", function(newValue, oldValue) {
console.log("User reference changed!");
});
Only triggers when user
is reassigned.
$scope.$watchCollection("user", function(newValue, oldValue) {
console.log("User properties changed!");
});
Triggers when any property of user
is modified.
6. Limitations of $watchCollection()
- Only watches the first level of properties.
- Does not detect deep changes in nested objects.
- If deep watching is required, use
$watch()
withtrue
:$scope.$watch("user", function(newValue, oldValue) { console.log("Deep watch detected changes"); }, true);
7. Cleaning Up Watchers
Always remove watchers when a scope is destroyed to prevent memory leaks.
var unwatch = $scope.$watchCollection("numbers", function(newValue, oldValue) {
console.log("Collection updated");
});
$scope.$on("$destroy", function() {
unwatch(); // Stop watching
});
Improves performance and prevents unnecessary memory usage.