In addition to storing data, scopes have three important functions that are fundamental to the way data binding works. These functions are called $watch
, $apply
, and $digest
.
$watch
$watch
makes up one side of two-way data binding: it enables you to set a callback function to be called whenever the value of a given expression changes. The callback function is often referred to as a watcher. A simple usage of $watch
is to update a weather variable every time the user changes city:
$scope.$watch('city', function(value) { $http.get('/remote/url/').success(function(data){ $scope.weather = data.temp; }) });
Internally, $watch
is a trivial function. Each scope maintains a list of watchers, called $scope.$$watchers.$watch
simply adds a new watcher, which includes some internal bookkeeping to keep track of the last computed value of the expression.
$apply
$apply
makes up the other half of two-way data binding: it informs AngularJS that something has changed and the values of $watch
expressions should be recomputed. You usually won’t have to call $apply
yourself, because AngularJS’s built-in directives (such as ngClick
) and services (such as $timeout
) call $apply
for you.
You’re most likely to run into $apply
in the context of custom event handlers. When an event occurs, such as a user clicking a button, or an outstanding HTTP request has completed, AngularJS needs to be informed that the model may have changed. Directives like ngClick
and ngDblclick
call $apply
internally for this reason.
// some changes ... $scope.weather = temp; $scope.$apply();
$digest
$digest
is the magic glue function that ties together $watch
and $apply
. You would be hard-pressed to find an example where you need to interface with $digest
directly rather than through $watch
and ``$apply.
At a high level, $digest
evaluates all the $watch
expressions in a scope, as well as the scope’s children, and fires the watcher callback on any that have changed. This process may seem simple, but there’s a subtle difficulty: a
watcher can change the scope, which in turn means that there may be other watchers that need to be informed of changes.