Search code examples
cssarraysangularjsangularjs-ng-repeat

AngularJS: Is there a way to use ng-repeat to create rows and columns from the same array of data?


I am attempting to create a loop that will run through an array and output the data into rows/columns. For each two items in the array, i'd like it to create a new row with two columns, like this:

<div class="row">
   <div class="col">1</div>
   <div class="col">2</div>
</div>

Here is an example of my array:

$scope.array = [1,2,3,4,5,6,7,8,9];

So, the overall end want would look like this:

<div class="row">
   <div class="col">1</div>
   <div class="col">2</div>
</div>
<div class="row">
   <div class="col">3</div>
   <div class="col">4</div>
</div>
<div class="row">
   <div class="col">5</div>
   <div class="col">6</div>
</div>
<div class="row">
   <div class="col">7</div>
   <div class="col">8</div>
</div>
<div class="row">
   <div class="col">9</div>
</div>

This is what I had originally attempted, but it was only showing up one column.

<div ng-repeat="item in array">
   <div ng-if="$index % 2 === 0" class="row">
      <div class="col">{{item}}</div>
   </div>
</div>

Any additional thoughts or direction on how I can achieve this? Thanks.


Solution

  • You were very close! Try this:

    <div ng-repeat="item in array">
       <div ng-if="$index % 2 === 0" class="row">
          <div class="col">{{item}}</div>
          <div ng-if="$index + 1 < array.length" class="col">
             {{array[$index + 1]}}
          </div>
       </div>
    </div>
    

    All that you were missing was the second column.