Mastering Web Application

(Rick Simeone) #1

Chapter 11
element.text(dateFilter(new Date(), 'hh:mm:ss'));
//repeat in 1 second
$timeout(update, 1000);


}

update();
}
};
})

Such a directive, used with the markup that would trigger the
$digest loop every second. This is why we can pass an optional, third parameter to
the $timeout service, which will indicate if scope.$apply should be called or not.
The better way of writing the update() function is shown as follows:


function update() {
element.text(dateFilter(new Date(), 'hh:mm:ss'));
$timeout(update, 1000, false);
}

We can avoid a $digest loop being triggered by the $timeout
service if we pass false as the third argument when registering a
timer.

Lastly, we can easily trigger a massive number of $digest loops by registering
a significant number of certain DOM event handlers, especially ones related to
mouse movements. For example, a very declarative, AngularJS-way of changing
an element's class (say, to switch it to active), when a mouse is positioned over it,
would be:


<div ng-class='{active: isActive}' ng-mouseenter ='isActive=true' ng-
mouseleave='isActive=false'>Some content</div>

While the preceding code works and keeps CSS class names where they belong
(HTML markup) it will trigger a $digest loop every time a mouse pointer travels
over a given DOM element. This shouldn't generate many problems if used
sparingly (on just a few DOM elements), but it might grind our application to a halt
if this pattern is repeated for a large number of elements. If you start to observe
performance issues linked to mouse events, consider rolling out your own, custom
directive where you could do direct DOM manipulations in response to DOM events
and model mutations.

Free download pdf