Mastering Web Application

(Rick Simeone) #1
Chapter 11

As an example of a situation where we can narrow down impacted scopes, let's
consider a typeahead (autocomplete) directive, shown as follows:


In this directive a pop up with autocomplete suggestion has its own scope holding
all the proposals and a reference to a currently selected item (California). Users can
navigate through the list of proposals using keyboard (up and down arrows) to change
a selected item. When a keyboard event is detected we need to call scope.$apply()
so AngularJS two-way data binding machinery kicks in, and an appropriate item is
highlighted. But keyboard navigation can only influence a scope of the pop up so
evaluating all the watches on all scopes in the entire application is clearly wasteful.
We can act smarter and call the $digest() method on the pop up's scope.


Remove unused watches


You might face a situation where a registered watch is needed only for a fraction of
the application's running time. AngularJS makes it possible to unregister obsolete
watches like:


var watchUnregisterFn = $scope.$watch('name', function (newValue,
oldValue) {
console.log("Watching 'name' variable");
...
});

//later on, when a watch is not needed any more:

watchUnregisterFn();

As you can see, a call to the scope.$watch method returns a function that can be
used to unregister a given watch when it is no longer needed.

Free download pdf