Mastering Web Application

(Rick Simeone) #1

Displaying and Formatting Data


<span ng-switch-when="false">
There are no items in the list.
</span>
</div>

Of course it would be possible to move the message-preparing logic to a controller to
avoid switch statements in a template, but it feels like this type of simple conditional
logic has its place in the view layer.


Fortunately, the latest version of AngularJS: the ng-if directive built-in is a very
handy tool for cases where you don't need power of a full if/else expression.


ngRepeat and multiple DOM elements


A slightly more serious issue is connected with the fact that, in its simplest form, the
ng-repeat repeater only knows how to repeat one element (with its children). This
means that ng-repeat can't manage a group of sibling elements.


To illustrate this let's imagine that we've got a list of items with a name and
description. Now, we would like to have a table where both the name and the
description are rendered as separate rows (). The problem is that we need to
add the tag just to have a place for the ng-repeat directive:


<table>
<tbody ng-repeat="item in items">
<tr>
<td>{{item.name}}</td>
</tr>
<tr>
<td>{{item.description}}</td>
</tr>
</tbody>
</table>

It looks like the ng-repeat directive needs a container element and forces us to
create a certain HTML structure. This might or might not be a problem depending on
how strictly you need to follow markup structure outlined by your web designers.


In the previous example we were lucky since an appropriate HTML container exists
(), but there are cases where there is no valid HTML element where the
ng-repeat directive could be placed. We could think of another example where we
would like to have an HTML output like:


<ul>
<!-- we would like to put a repeater here -->
<li><strong>{{item.name}}</strong></li>
Free download pdf