【问题标题】:Finding an ng-repeat index?找到一个 ng-repeat 索引?
【发布时间】:2014-03-23 07:54:17
【问题描述】:

我可以在 Angular.js 中做到这一点:

<tr ng-repeat="cust in customers">
  <td>
    {{ cust.name }}
  </td>
</tr>

这将通过将每个客户放入自己的&lt;tr&gt; 来遍历所有客户。

但是如果我想要两个客户合二为一&lt;tr&gt; 怎么办?我将如何做到这一点?

我通常通过弄乱索引和模值来做到这一点,但我不知道如何在这里做到这一点。

【问题讨论】:

  • 数据(客户)如何告诉您将哪些放在一起?
  • @nachinius 啊——它们是按数组排序的——这就是我放入它们的顺序。这就是为什么我考虑使用索引来解决这个问题。

标签: javascript html angularjs angularjs-ng-repeat


【解决方案1】:

事实证明,这可以在没有任何自定义过滤器或更改数据格式的情况下完成,尽管它确实需要一些额外的标记。起初我认为这是不可能的,因为您不能在 ng-repeat 的表中使用span 或任何类似的东西。但是This answer 指出您可以使用tbody

所以这只是使用ng-if 指令(如果表达式为真则呈现html)、$index 变量(由ng-repeat 提供)和$even 变量(也由ng-repeat$index 为偶数时为真

我在this Plunker创建了一个演示

<div  ng-controller="MainCtrl">
  <table>
    <tbody ng-repeat="cust in customers">
      <tr ng-if="$even">
        <td>{{customers[$index].text}}</td>
        <td>{{customers[$index+1].text}}</td>
      </tr>
    </tbody>
  </table>
</div>

这当然只有在你有两列时才有效,如果你有更多呢?好吧,您也可以将完整的表达式放入ng-if 而不仅仅是一个变量。所以你可以像这样使用模值:

    <tbody ng-repeat="cust in customers">
      <tr ng-if="($index % 3) == 0">
        <td>{{customers[$index].text}}</td>
        <td>{{customers[$index+1].text}}</td>
        <td>{{customers[$index+2].text}}</td>
      </tr>
    </tbody>

【讨论】:

    猜你喜欢
    • 2014-06-11
    • 2014-09-29
    • 2013-01-26
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多