2

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.

tvkanters
  • 3,519
  • 4
  • 29
  • 45
Lucas
  • 16,930
  • 31
  • 110
  • 182
  • how would the data (customers) tell you which to put together? – nachinius Mar 22 '14 at 22:26
  • @nachinius Ah - they're ordered in an array - and that's the order by which I put them in. This is why I was thinking of using indexes for this problem. – Lucas Mar 22 '14 at 22:28
  • Check out the answers here: http://stackoverflow.com/questions/21644493/how-to-split-the-ng-repeat-data-with-three-columns-using-bootstrap – Ciaran Phillips Mar 22 '14 at 23:34

1 Answers1

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>
Community
  • 1
  • 1
Ciaran Phillips
  • 603
  • 1
  • 6
  • 9