Writing Robust AngularJS Web Applications
Limit the number of turns per $digest loop
Models that are harder to stabilize will require more turns of a $digest loop. As a
result all the watches will be re-evaluated multiple times. Typically a $digest loop
requires two turns but it might quickly grow to the configured limit (10 by default) if
a model never stabilizes.
Try to think of all the conditions that are necessary to stabilize a newly registered
watch. Expressions that are highly unstable shouldn't be part of the watch expression
but instead should be computed outside of a $digest loop.
Optimizing memory consumption
AngularJS uses a dirty-checking mechanism to decide if a given part of the model
has changed, and if an action (updating DOM properties, changing other model
values, and so on) should be taken as a consequence. An efficient values comparison
algorithm is crucial for the proper functioning of the dirty-checking mechanism.
Avoid deep-watching whenever possible
By default AngularJS uses identity comparison (for objects) or values comparison
(for primitive types) to detect changes in the model. Such comparisons are fast and
straightforward but there are cases where we might want to compare objects on the
property-by-property basis (so called deep-compare).
Let's consider a typical User object that has a number of different properties:
$scope.user = {
firstName: 'AngularJS',
lastName: 'Superhero',
age: 4,
superpowers: 'unlimited',
// many other properties go here...
};
Assuming that we would like to have the full name of this user in one single model
variable, updated automatically whenever one of the first or last name changes, we
could create a new watch on a $scope:
$scope.$watch('user', function (changedUser) {
$scope.fullName =
changedUser.firstName + ' ' + changedUser.lastName;
}, true);