有条件地在ng-repeat中添加行

时间:2014-08-13 04:18:54

标签: angularjs angularjs-ng-repeat ng-repeat

我在AngularJS中有一个简单的重复表格行

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

我的item对象上有一个comment属性,如果该注释包含一个值,我想在其余元素后面的行中单独显示该行让它跨越整行。这类事可能吗?我看了ng-repeat-end,但这似乎不是我想要的,而且我不能只是添加额外的&lt; tr&gt; ng-repeat中的元素,因为它是无效的HTML。

1 个答案:

答案 0 :(得分:4)

您可以通过ng-repeat-startng-repeat-end使用 ng-repeat's 特殊重复开始和结束点。

<强> 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>

更新:如果评论是字符串,则只需删除ng-repeat端点的ng-repeat-end,然后添加一个ng-if表达式,以验证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>