Beginning AngularJS

(WallPaper) #1

CHApTer 5 ■ DIreCTIveS


Event-Handling Directives

We have seen ngClick already, though Angular JS comes with similar directives for handling the usual browser events,
such as ondblclick, onblur, onfocus, and onsubmit. Each directive works pretty much as you would expect and is
named using the same format. So, for the list of events I just mentioned, we would have the corresponding Angular JS
versions: ngDblclick, ngBlur, ngFocus, and ngSubmit.
You don’t have to use these directives, as Angular JS in no way prevents you from using the regular JavaScript
event handlers. However, it is generally recommended that you do use them, especially if you want to stay within the
Angular JS framework. For example, a big difference between regular events and their Angular JS equivalents is that
the equivalents take Angular JS expressions. This means that you have access to the implicitly available $scope object,
among other things.


Using the API Documentation

There are far more directives than I can cover here, though all of them are well-documented at https://docs.
angularjs.org/api/ng/directive/. This documentation is quite good, though it can be a little terse at times. It is
well worth familiarizing yourself with it. Following is a brief guide to how it is usually presented (see Table 5-2).


Figure 5-3. Repeating with ngRepeat


This format follows the variable in collection pattern. I chose the name “city” for the variable, and the collection
is the array of cities. Another important thing to know about ngRepeat is that it creates, at each pass through the loop,
a new scope object, each one quite distinct from the controller’s own $scope object. In fact, this is why we can have
different values for variables, such as $index and city.

Free download pdf