简体   繁体   中英

Open and close a div after every “x” element

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>

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/

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>`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM