0

Let's say I have 8 items in my array. While looping through this array, I would want to split them into 3 items/page which would give me 3 pages.

The logic is clear but I don't know how one can achieve this using ng-repeat. If there is no direct way, I'm also open to indirect ways.

In essence, I would like to do something like this:

JS

$scope.items = ["A", "B", "C", "D", "E", "F", "G", "H"];
$scope.pages = Math.ceil($scope.items.length/3);

HTML

<div class="box">
    <div class="items" ng-repeat="page in pages">
        <!-- put 3 items here and then create a new ".items" div with the next 3 items and so on -->
    </div>
</div>

Expected Output

<div class="box">
    <div class="items">
        <p>A</p>
        <p>B</p>
        <p>C</p>
    </div>
    <div class="items">
        <p>D</p>
        <p>E</p>
        <p>F</p>
    </div>
    <div class="items">
        <p>G</p>
        <p>H</p>        
    </div>
</div>
asprin
  • 9,579
  • 12
  • 66
  • 119
  • Check this once https://stackoverflow.com/questions/35255705/angularjs-can-i-use-a-filter-to-chunk-an-array-in-ng-repeat – Satpal Jun 13 '17 at 11:39

2 Answers2

1

The idea to acheive your goal is to split your primary array into smallest arrays by using the splicing function for arrays : https://www.w3schools.com/jsref/jsref_splice.asp

Your splitting function may look like that :

var _split = function(res,arr, n) {

  while (arr.length) {
    res.push(arr.splice(0, n));
  }

}

I have created a jsfindle to illustrate that with your requierements : http://jsfiddle.net/ADukg/11761/

aorfevre
  • 5,034
  • 3
  • 21
  • 51
1

Try this: in the angular controller:

$scope.items = ["A", "B", "C", "D", "E", "F", "G", "H"];  
$scope.pages = Math.ceil($scope.items.length/3);
$scope.itemsArray=[];
while($scope.items.length>0){
        $scope.itemsArray.push($scope.items.splice(0,$scope.pages));
}

In html:

<div ng-repeat="o in itemsArray">
<p ng-repeat="it in o"> {{it}} </p>
</div>`
Pablo
  • 34
  • 3