Mastering Web Application

(Rick Simeone) #1

Displaying and Formatting Data


The mentioned variables come in very handy in many real-life situations. For
example, in the sample SCRUM application we can rely on the $last variable to
properly render links in a breadcrumb element. For the last (selected) part of the
path there is no need to render links, while the element is needed for other parts
of the path.


We can model this UI using the following code:


<li ng-repeat="breadcrumb in breadcrumbs.getAll()">
<span class="divider">/</span>
<ng-switch on="$last">
<span ng-switch-when="true">{{breadcrumb.name}}</span>
<span ng-switch-default>
<a href="{{breadcrumb.path}}">{{breadcrumb.name}}</a>
</span>
</ng-switch>
</li>

Iterating over an object's properties


Usually the ng-repeat directive is used to display entries from a JavaScript array.
Alternatively it can be used to iterate over properties of an object. In this case the
syntax is slightly different:


<li ng-repeat="(name, value) in user">
Property {{$index}} with {{name}} has value {{value}}
</li>

In the preceding example, we can display all the properties of a user object as an
unordered list. Please note that we must specify variable names for both a property
name and its value using a bracket notation (name, value).


The ng-repeat directive will, before outputting results, sort property
names alphabetically. This behavior can't be changed so there is no way
of controlling the iteration order while using ng-repeat with objects.

The $index variable can still be used to get a numerical position of a given property
in a sorted list of all properties.

← Previous
Free download pdf