Technology, Continued...

Ramblings about business, technology, development and my life

NAVIGATION - SEARCH

Ng-repeat-start and ng-repeat-end with a child collection

If you have multiple table rows you want to create for each item in a collection you’re enumerating through with ng-repeat, you have to use special directives to do so.  Here’s what most people try first:

<div ng-repeat="item in col">
    <tr>
        <td>{{ item.name }}</td>
    </tr>
    <tr>
        <td>{{ item.description }}</td>
    </tr>
</div>

However, this doesn’t work, because trs can’t be contained in a div.  Fortunately, Angular 1.2 added the directives ng-repeat-start and ng-repeat-end for just this reason.  Instead of the above, you can do it this way:

<tr ng-repeat-start="item in col">
    <td>{{ item.name }}</td>
</tr>
<tr ng-repeat-end>
    <td>{{ item.description }}</td>
</tr>

This basically gives you a compound repeater where you can contain multiple sibling elements within the repeat.

One interesting situation I ran into was where I needed to also repeat a child collection of item above, within the col repeat.  Fortunately, you can combine ng-repeat-start/ng-repeat-end and ng-repeat on the same element, as shown below.  The example here will show you the name of the item in the first row, and then give you rows for each child of the item.  This will be repeated for as many items and children as there are.

<tr ng-repeat-start="item in col">
    <td>{{ item.name }}</td>
</tr>
<tr ng-repeat-end ng-repeat="child in item.children">
    <td>{{ child.name }}</td>
</tr>

Hopefully this helps someone else out there.