Skip to content Skip to sidebar Skip to footer

Finding An Ng-repeat Index?

I can do this in Angular.js: {{ cust.name }} Which would iterate through all the customers by p

Solution 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

<divng-controller="MainCtrl"><table><tbodyng-repeat="cust in customers"><trng-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>

Post a Comment for "Finding An Ng-repeat Index?"