Soubriquet
Soubriquet

Reputation: 3330

Creating a new table row with ng-repeat and <td> if mod N columns

I'm trying to use ng-repeat to create two columns. I have a list of items i.e. ['green', 'red', 'blue', 'yellow'] and want to create two columns with two items in each. However, I'm not sure how to start a new row if the current index is mod 2.

green   red
blue    yellow

Is there a way of doing this?

Upvotes: 2

Views: 1120

Answers (2)

JimL
JimL

Reputation: 2541

I would just prepare the data before passing it to the DOM, you can find lots of "chunk" implementations online

['green', 'red', 'blue', 'yellow']

split into suitable chunks:
[ [ "green", "red" ], [ "blue", "yellow" ] ]

code:

<div data-ng-controller="MyCtrl">
    <table>
        <tr data-ng-repeat="row in tableData">
            <td data-ng-repeat="color in row">
                {{ color }}
            </td>
        </tr>
    </table>
</div>

<script>
var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.colors = ['green', 'red', 'blue', 'yellow'];
    $scope.tableData = chunk($scope.colors, 2);
}

function chunk (arr, len) {
  var chunks = [],
      i = 0,
      n = arr.length;
  while (i < n) {
    chunks.push(arr.slice(i, i += len));
  }
  return chunks;
}
</script>

Output

green   red
blue    yellow

http://jsfiddle.net/oyz0f07n/

Upvotes: 2

Aditya Sethi
Aditya Sethi

Reputation: 10586

You can control it via css

If you are using bootstrap

<div class="row">
    <div data-ng-repeat="color in colors" class="col-md-6"> {{ color }} </div>
</div>

If you are not using bootstrap, you can set a class in your css with 50% width and add that class in the div. Something like this

CSS

.width-50 {
    width: 50%;
}

HTML

    <div data-ng-repeat="color in colors" class="width-50"> {{ color }} </div>

Upvotes: 0

Related Questions