Mastering Web Application

(Rick Simeone) #1
Chapter 4

Repeater's implementation is highly optimized and will try to minimize
number of DOM changes needed to reflect data structure in the DOM
tree.

Internally the ng-repeat might choose to move DOM nodes around (if you move
an element in array), delete a DOM node if an element is removed from the array
and insert new nodes if additional elements end up in the array. Regardless of the
strategy chosen by a repeater behind the scenes it is crucial to realize that it is not a
simple for loop that will run once. The ng-repeat directive behaves more like an
observer of a data that tries to map entries in a collection to DOM nodes. The process
of data-observing is continuous.


Getting familiar with the ngRepeat directive


The basic usage and syntax is very simple:


<table class="table table-bordered">
<tr ng-repeat="user in users">
<td>{{user.name}}</td>
<td>{{user.email}}</td>
</tr>
</table>

Here the users array is defined on a scope and contains typical user objects with
properties like: name, email, and so on. The ng-repeat directive will iterate over
users' collection and create a DOM element for each entry in a collection.


The ng-repeat directive creates a new scope for each element of a
collection it iterates over.

Special variables


AngularJS repeater will declare a set of special variables in a scope created for each
and every individual entry. Those variables can be used to determine a position of an
element within a collection:



  • $index: It will be set to a number indicating index of an element in a
    collection (indexes start at 0)

  • $first, $middle, $last: These variables will get a Boolean value according
    to element's position

Free download pdf