Optimizing the application using $watchCollection
AngularJS offers the $watchCollection
intermediate watch type to register a listener that utilizes a shallow watch depth for comparison. The $watchCollection
type will register a change event when any of the object's properties are modified, but it is unconcerned with what those properties refer to.
How to do it…
This watcher is best used with arrays or flat objects that undergo frequent top-level property modifications or reassignments. Currently, it does not provide the modified property(s) responsible for the callback, only the entire objects, so the callback is responsible for determining which properties or indices are incongruent. This can be done as follows:
$scope.myObj = { myPrimitive: 'Go Bears!', myArray: [3,1,4,1,5,9] }; // watch myObj and all top-level properties by reference $scope.$watchCollection('myObj', function(newVal, oldVal, scope) { // callback logic }); // watch myObj.myArr and all its elements by reference $scope...