Using ng-repeat-start in AngularJS

14 Mar 2019, 15:03
by CodeOoze

You are probably familiar with the use of ng-repeat to repeat the DOM element it is attached to. One common use is rendering table columns using ng-repeat. The limitation of this approach is that ng-repeat will only repeat the element it is attached to, such as the <td> tag. As of AngularJS 1.2 you can define repeat start and end points using ng-repeat-start and ng-repeat-end. This means you can repeat a number of elements instead of just the first one.

Using ng-repeat

Let’s take a look at an example of ng-repeat to render a table. Suppose we have array of objects metaData which describes our table data. A second array of objects data contains the table data itself.

This is a perfectly valid approach. But what if you needed to render additional columns using <td> without altering the data arrays? You can’t do it easily with ng-repeat (you could create a custom directive, but let’s not go there).

Using ng-repeat-start

In AngularJS 1.2 you can use ng-repeat-start and ng-repeat-end. I’ll explain it’s usage by building on the previous example. Say you wanted an additional column to render a button for each row after the “Age” column.

The first <th> and <td> elements now use ng-repeat-start instead of ng-repeat, otherwise they remain unchanged.

A second <th> element is added to conditionally render an additional table header. This also marks the end of the first ng-repeat with ng-repeat-end.

A second <td> element is added to conditionally render the button column. This also marks the end of the second ng-repeat with ng-repeat-end.