Mastering Web Application

(Rick Simeone) #1

Displaying and Formatting Data


The ng-class directive can also accept arguments of type string or
array. Both arguments can contain a list of CSS classes (coma-separated
in case of string) to be added to a given element.

DOM event handlers


Our UI wouldn't be very useful if users couldn't interact with it (either by using
a mouse, a keyboard or touch events). The good news is that registering event
handlers is a child's play with AngularJS! Here is an example of reacting to a
click event:


<button ng-click="clicked()">Click me!<button>

The clicked() expression is evaluated against a current $scope which makes it very
easy to call any method defined on that scope. We are not limited to simple function
calls; it is possible to use expressions of an arbitrary complexity, including ones that
accept arguments:


<input ng-model="name">
<button ng-click="hello(name)">Say hello!<button>

Developers new to AngularJS often try to register event handler as follows:
ng-click="{{clicked()}}" or ng-click="sayHello({{name}})"
that is using interpolation expression inside an attribute value. This is not
needed and it won't work correctly. What would happen is that AngularJS
would parse and evaluate an interpolation expression while processing
the DOM. This first step of processing would evaluate an interpolation
expression and use the result of this evaluation as an event handler!

AngularJS has the built-in support for the different events with the
following directives:



  • Click events: ngClick and ngDblClick

  • Mouse events: ngMousedown, ngMouseup, ngMouseenter, ngMouseleave,
    ngMousemove and ngMouseover

  • Keyboard events: ngKeydown, ngKeyup and ngKeypress

  • Input change event (ngChange): The ngChange directive cooperates with
    the ngModel one, and let us to react on model changes initiated by user input.

Free download pdf