Ronald
Ronald

Reputation: 336

angularJS - Repeating tr's in a table, but dynamically adding more rows while looping

Since examples always tell more then just words here is what I would like to do in another language

<tr>
    <c:forEach items="${items}" var="item"> 
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <c:if test="${item.showWarning}">
         </tr><tr><td colspan="3">${item.warning}</td>
      </c:if>
</tr>

So this will loop over a set of items and show some properties of these items. If there is a warning, a new row will be added underneath the current row in which the warning will be shown. However, how can I do this in angularJs? If I put a ng-repeat on the tr, it will stop at the first end tag of tr. I have read on some other threads that this is not very easily done, but how can it be done? And yes, I really do want to use a table. Here is my contrived example with angularjs which is obviously not working as I would like it to. Any pointers how this can be done?

JSBin example with tr-ng-repeat

Upvotes: 9

Views: 28084

Answers (3)

callmekatootie
callmekatootie

Reputation: 11228

One solution that I can think of is having multiple tbody tags within the same table. Here is a discussion on the use of multiple tbody tags within the same table.

So, for your issue, you could have the following setup:

<table ng-controller="ItemController">
    <thead>
        <th>Name</th>
        <th>Description</th>
        <th>warning?</th>
    </thead>
    <tbody ng-repeat="item in items">
        <tr>
            <td>{{item.name}}</td>
            <td>{{item.description}}</td>
            <td>{{item.warning}}</td>
        </tr>
        <tr ng-show="item.warning">
            <td colspan="3" style="text-align: center">Warning !!!</td>
        </tr>
    </tbody>
</table>

Repeat the table body as many times as there are entries for the table and within it have two rows - one to actually display the row entry and one to be displayed conditionally.

Upvotes: 11

Liviu T.
Liviu T.

Reputation: 23664

Currently (1.0.7/1.1.5) you can't output data outside the ng-repeat, but version 1.2(see youtube video AngularJS 1.2 and Beyond at 17:30) will bring the following syntax(adapted to your example):

<tr ng-repeat-start="item in items">
  <td>...</td>
  <td>...</td>
  <td>...</td>
</tr>
<tr ng-repeat-end ng-show="item.showWarning">
  <td colspan="3">{{item.warning}}</td>
</tr>

The idea is that whatever is between -start and -end will be repeated including the -end element.

Upvotes: 20

Mark Coleman
Mark Coleman

Reputation: 40863

You can repeat over the tbody

<tbody ng-repeat="item in items">
  <tr>
   <td>{{item.name}}</td>
   <td>{{item.description}}</td>
   <td>{{item.warning}}</td>
  </tr>
  <tr ng-show="item.warning">
    <td colspan="3">Warning !!!</td>
  </tr>
</tbody>

Also you do not need to wrap the ng-show expression in {{}}, you can just use item.warning

Upvotes: 0

Related Questions