Reputation: 9833
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:
$scope.items = ["A", "B", "C", "D", "E", "F", "G", "H"];
$scope.pages = Math.ceil($scope.items.length/3);
<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>
<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>
Upvotes: 0
Views: 62
Reputation: 34
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>`
Upvotes: 1
Reputation: 5064
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/
Upvotes: 1