Mastering Web Application

(Rick Simeone) #1

Writing Robust AngularJS Web Applications


Here the getNameLog() is simply returning a name and uses console.log to
simulate an "expensive" operation. If we start to type into the field we
will notice that the getNameLog() expression is evaluated on each keystroke. This
happens even if results of the evaluation are never visible on a screen!


Remember that expensive watches might not have any visual effects on
a screen. If the hidden part of the display slows down your application
consider using the ng-switch family of directives. Those directives
physically remove invisible DOM elements from the DOM tree.

Call Scope.$digest instead of calling Scope.$apply when you


know impacted scopes


In the first part of this chapter, we saw that AngularJS needs to traverse all the scopes
in the whole application when executing its $digest loop. This is done to cater for
the case where change triggered in one scope can mutate model in one of the parent
scopes. But there are times where we know exactly which scopes are impacted by a
given change, and we can use this knowledge to our advantage.


If we know exactly which scopes are impacted by model mutations we can call
the scope.$digest method on the topmost impacted scope, instead of calling
scope.$apply. The scope.$digest method will run a $digest loop on a limited
subset of scopes. Only watches declared on a scope on which the method was
called, plus child scopes, are going to be inspected for model changes. This can
significantly reduce number of watch expressions to be evaluated and thus speed
up the $digest loop.

Free download pdf