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.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply