Finding an ng-repeat index?

邮差的信 提交于 2020-01-04 10:39:31

问题


I can do this in Angular.js:

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

Which would iterate through all the customers by putting each in a <tr> of its own.

But what if I wanted two customers in one <tr>? How would I accomplish that?

I normally do that by messing around with indexes and modulus values, but I'm not sure how to do that here.


回答1:


It turns out this can be done without any custom filters or changing the format of your data, though it does require some extra markup. I thought this woudn't be possible at first as you can't use a span or anything similar within the table for your ng-repeat. This answer however, points out that you can use a tbody.

So it's just a case of using the ng-if directive (which renders html if the expression is true), the $index variable (provided by ng-repeat) and the $even variable (which is also provided by ng-repeat and is true when $index is even

I've created a demo in 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>

This would of course only work if you have two columns, what if you have more? Well you can also put a full expression into ng-if rather than just a variable. So you can use modulus values like this:

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


来源:https://stackoverflow.com/questions/22584219/finding-an-ng-repeat-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!