Creating a parent/child table in Angular

Home / Creating a parent/child table in Angular

A while back, I needed a simple way to create a table with parent/child details in Angular. ng-repeat has some handy little known features to make creating this type of table easy.

My data is an array of objects and each object within that list has an array of child objects. The desired output is a table showing my array of objects with a button or some other mechanism which will expand an area below each object and reveal the child (detail) objects.

To display an array, we would use ng-repeat to repeat over the array. That’s simple. ng-repeat can take advantage of ng-repeat-start and ng-repeat-end directives to provide for greater control of the rendered items.

In this case, our “start” is repeating over the parent objects. When that “ends,” we will repeat over the child objects. Additionally, we will use ng-if to toggle visibility of the child items.

The mechanism looks like kind of like this:

<table class="table">
    <tr class="item" ng-class-even="'even'" ng-class-odd="'odd'" ng-repeat-start="item in vm.items">
            {{ }}
            <button class="btn btn-default" ng-click="vm.showHistory(item)" 
                ng-bind="item.showHistory ? 'Hide History' : 'Show History'" />
        <td ng-bind=""></td>
        <td ng-bind=""></td>

You can see above that we give out top level “items” to the ng-repeat-start directive. This is just like the regular ng-repeat expect that it looks for an ng-repeat-end. Below, you can see that the ng-repeat-end is specified. In addition to the ng-repeat-end, though, there is an ng-repeat iterating over the item’s child (history in this case) collection.

    <tr class="history" ng-class-even="'even'" ng-class-odd="'odd'" ng-repeat-end
        ng-repeat="history in item.histories" ng-if="item.showHistory">
        <td ng-bind=""></td>

That’s really it. This mechanism can be used to “post render” as needed at the end of repeat. It just so happens that at the end could be another repeat.

See the plunkr below for a demo.

Leave a Reply