Gargoyle
Gargoyle

Reputation: 10324

Conditionally add row in ng-repeat

I've got a simple repeating table-row in AngularJS

<tr ng-repeat="item in items">
    <td>{{ item.prop1 }}</td>
    <td>{{ item.prop2 }}</td>
</tr>

My item object has a comment property on it, and if that comment contains a value, I want to display that in a row all by itself on the line right after the rest of the elements and have it span the entire row. Is that type of thing possible? I looked at ng-repeat-end but that doesn't seem to be what I want, and I can't just add and extra <tr> element inside the ng-repeat as that'd be invalid HTML.

Upvotes: 3

Views: 4548

Answers (1)

ryeballar
ryeballar

Reputation: 30098

You can use ng-repeat's special repeat start and end points via ng-repeat-start and ng-repeat-end.

DEMO

HTML

<table ng-controller="PostController">
  <tr ng-repeat-start="post in posts">
    <td>{{post.content}}</td>
  </tr>
  <tr ng-repeat-end ng-repeat="comment in post.comments">
    <td>{{comment.content}}</td>
  </tr>
</table>

UPDATE: If the comment is a string, then simply remove the ng-repeat at the ng-repeat-end end point and add an ng-if expression that validates the existence of post.comment.

DEMO

HTML

<table ng-controller="PostController">
  <tr ng-repeat-start="post in posts">
    <td>{{post.content}}</td>
  </tr>
  <tr ng-repeat-end ng-if="post.comment">
    <td>{{post.comment}}</td>
  </tr>
</table>

Upvotes: 5

Related Questions