-2

I am using ng-repeat to iterate over an array to generate <li>. But i want to stack every 2 li into div.

<li ng-repeat="item in items">{{item.name}}</li>

I want the output to be like this:

<ul>
   <div>
       <li>A</li>
       <li>B</li>
   </div>
   <div>
       <li>C</li>
       <li>D</li>
   </div>
</ul>

How should i achieve this with ng-repeat? Thanks in advance for any help.

ashfaq.p
  • 5,379
  • 21
  • 35

2 Answers2

2

Apply ng-repeat on ul and li will act as a template which will be generated for each item.

Ex :

<ul ng-repeat="item in items">
        <li>{{item.name}}</li>
     </ul>

This will result in

<ul>
   <li>name1</li>
   <li>name2</li>
   <li>name2</li>
</ul>

If you have a collection consisting of 10 items , you can split them in multiple collections each of size 2 and then apply ng-repeat with each collection on div to get the output you want.

Nish26
  • 969
  • 8
  • 16
2

Although it is invalid to put div inside ul but to illustrate. i have made a function to split your array into group of 2 element array contained in wrapper array

Or You can also use splice method

Working Demo 1

angular.module('testApp',[]).controller('testCtrl', function($scope) {
  $scope.items=['1','2','3'];
  
  
  $scope.groupByTwo = function (array)
    {
    var newarray =[];
    index=0;
    for(a=0;a<array.length;a++){
       if(a==0 || a%2==0){
          newarray[index]=[];
          newarray[index].push(array[a]);
      }else{
         newarray[index].push(array[a]);
      }
    if(a!=0)
    index++;
    
    }
  return newarray;
}
  $scope.items=$scope.groupByTwo($scope.items);
});
div {
  background:pink; 
  border:1px dotted black;
  margin-top:15px;}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="testApp" ng-controller="testCtrl">
  

<ul>
   <div  ng-repeat="item in items">
       <li ng-repeat="i in item">{{i}}</li>
       
   </div>
   
</ul>

Working Demo 2

You can also use splice method

angular.module('testApp',[]).controller('testCtrl', function($scope) {
  $scope.items=['1','2','3'];
  var i,j,temparray=[],chunk = 2;
  for (index=0,i=0,j=$scope.items.length; i<j; i+=chunk,index++) {
    temparray [index]= $scope.items.slice(i,i+chunk);
   }
   $scope.items =temparray;
  
 
});
div {
  background:pink; 
  border:1px dotted black;
  margin-top:15px;}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="testApp" ng-controller="testCtrl">
  

<ul>
   <div  ng-repeat="item in items">
       <li ng-repeat="i in item">{{i}}</li>
       
   </div>
   
</ul>
A.B
  • 20,110
  • 3
  • 37
  • 71