Mastering Web Application

(Rick Simeone) #1
Chapter 4

Mentioned DOM event handlers can accept a special argument $event in their
expression, which represents the raw DOM event. This allows us to get access to
lower-level properties of an event, prevent it default action, stop its propagation,
and so on. As an example we can see how to read the position of a clicked element:


<li ng-repeat="item in items" ng-click="logPosition(item, $event)">
{{item}}
</li>

Where the logPosition function is defined on a scope like follows:


$scope.readPosition = function (item, $event) {
console.log(item + ' was clicked at: ' + $event.clientX + ',' +
$event.clientY);
};

While the $event special variable is exposed to event handlers it
shouldn't be abused to do extensive DOM manipulations. As you
remember from Chapter 1, Angular Zen AngularJS is all about declarative
UI and DOM manipulation should be restricted to directives. This is
why the $event argument is mostly used inside directive's code.

Working effectively with DOM-based templates


It is not very common to see a template system employing live DOM and HTML
syntax but this approach turns out to work surprisingly well in practice. People used
to other, string-based template engines might need some time to adjust, but after a
few initial hops writing DOM-based templates becomes a second nature. There are
just a couple of caveats.


Living with verbose syntax


Firstly, the syntax for some of the constructs might be a bit verbose. The best example
of this slightly annoying syntax for the ng-switch family of directives some common
use cases might simply require a lot of typing. Let's consider a simple example of
displaying a different message based on a number of items in a list:


<div ng-switch on="items.length>0">
<span ng-switch-when="true">
There are {{items.length}} items in the list.
</span>
Free download pdf