The Three Watch Depths of AngularJS

Posted on by Tero Parviainen

Update: A revised version of this is now in the official Angular docs.

There are three different mechanisms for watching a value on an Angular scope: Reference watches, collection watches, and equality watches. The difference between the three is in the depth in which they watch their values.

Choosing the most appropriate watch mechanism is important, not only because the three mechanisms behave differently, but also because they have very different performance characteristics.

This short article describes the differences between the three watch depths.

Reference Watches

You register a reference watch by providing a falsy value as the third argument to $watch or by just omitting the third argument:

$scope.$watch(…, …, false);

or

$scope.$watch(…, …);

Of the three mechanisms this is the most efficient both in terms of computation and memory, since it doesn't do copying or traversal. It merely keeps a reference to the value around for comparison. The references are compared using the strict equality operator ===.

Reference watches are used internally by Angular in:

Collection Watches

You register a collection watch by calling $watchCollection:

$scope.$watchCollection(…, …);

Collection watches watch for changes in arrays, array-like objects, and objects. They are triggered by new, removed, replaced, and reordered items, keys, or values in those arrays and objects. They do not, however, watch the items, keys, or values themselves.

Collection watches keep an internal copy of the array or object, and traverse the old and new values in each digest cycle, checking for changes using the strict equality operator ===. The implementation attempts to avoid all unnecessary traversal. The items within the collection are just referenced, not copied.

Collection watches are used internally by Angular in the ngRepeat directive.

Equality Watches

You register an equality watch by providing a truthy value as the third argument to $watch:

$scope.$watch(…, …, true);

Equality watches watch for any changes within the values, which may be arbitrarily nested objects and arrays. This means they also need to keep full copies of the values around and traverse them in each digest cycle. This makes equality watches the most expensive of the three mechanisms.

Values are compared using angular.equals and copied using angular.copy.

Equality watches are used internally by Angular in the ngClass and ngStyle directives on their attribute expressions.

Know Your AngularJS Inside Out

Build Your Own AngularJS

Build Your Own AngularJS helps you understand everything there is to understand about Angular. By creating your very own implementation of Angular piece by piece, you gain deep insight into what makes this framework tick. Say goodbye to fixing problems by trial and error and hello to reasoning your way through them

Early Access eBook Available Now

comments powered by Disqus