Haider Alee Haider Alee - 4 months ago 15
AngularJS Question

Adding <ul></ul> after every 2nd <li> with angular ngRepeat

I have a ul and I apply ngRepeart on li but I want after every 2nd li it's create new ul Like This.

is this possible ?

<ul>
<li>simth</li>
<li>aryan</li>
</ul>
<ul>
<li>john</li>
<li>mark</li>
</ul>
<ul>
<li>cooper</li>
<li>lee</li>
</ul>


and this is my angular.js code

function myCrtl($scope){
$scope.nameList= [{
name:'simth'
},{
name:'aryan'
},{
name:'john'
},{
name:'mark'
},{
name:'cooper'
},{
name:'lee'
}]
}

Answer

You can split your array into chunks. Please see demo below

var app = angular.module('app', []);

app.controller('homeCtrl', function($scope) {


  $scope.nameList = [{
    name: 'simth'
  }, {
    name: 'aryan'
  }, {
    name: 'john'
  }, {
    name: 'mark'
  }, {
    name: 'cooper'
  }, {
    name: 'lee'
  }]

  Array.prototype.chunk = function(chunkSize) {
    var array = this;
    return [].concat.apply([],
      array.map(function(elem, i) {
        return i % chunkSize ? [] : [array.slice(i, i + chunkSize)];
      })
    );
  }

  $scope.temparray = $scope.nameList.chunk(2)


});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="homeCtrl">

    <ul ng-repeat="gr in temparray">
      <li ng-repeat="person in gr">{{person.name}}</li>
    </ul>
  </div>
</div>

Comments