chrisdew chrisdew - 2 months ago 23
AngularJS Question

How to use ng-repeat without an html element

I need to use

ng-repeat
(in AngularJS) to list all of the elements in an array.

The complication is that each element of the array will transform to either one, two or three rows of a table.

I cannot create valid html, if
ng-repeat
is used on an element, as no type of repeating element is allowed between
<tbody>
and
<tr>
.

For example, if I used ng-repeat on
<span>
, I would get:

<table>
<tbody>
<span>
<tr>...</tr>
</span>
<span>
<tr>...</tr>
<tr>...</tr>
<tr>...</tr>
</span>
<span>
<tr>...</tr>
<tr>...</tr>
</span>
</tbody>
</table>


Which is invalid html.

But what I need to be generated is:

<table>
<tbody>
<tr>...</tr>
<tr>...</tr>
<tr>...</tr>
<tr>...</tr>
<tr>...</tr>
<tr>...</tr>
</tbody>
</table>


where the first row has been generated by the first array element, the next three by the second and the fifth and sixth by the last array element.

How can I use ng-repeat in such a way that the html element to which it is bound 'disappears' during rendering?

Or is there another solution to this?




Clarification: The generated structure should look like below. Each array element can generate between 1-3 rows of the table. The answer should ideally support 0-n rows per array element.

<table>
<tbody>
<!-- array element 0 -->
<tr>
<td>One row item</td>
</tr>
<!-- array element 1 -->
<tr>
<td>Three row item</td>
</tr>
<tr>
<td>Some product details</td>
</tr>
<tr>
<td>Customer ratings</td>
</tr>
<!-- array element 2 -->
<tr>
<td>Two row item</td>
</tr>
<tr>
<td>Full description</td>
</tr>
</tbody>
</table>

Answer

Update: If you are using Angular 1.2+, use ng-repeat-start. See @jmagnusson's answer.

Otherwise, how about putting the ng-repeat on tbody? (AFAIK, it is okay to have multiple <tbody>s in a single table.)

<tbody ng-repeat="row in array">
  <tr ng-repeat="item in row">
     <td>{{item}}</td>
  </tr>
</tbody>