AngularJS ng-repeat rows / ul

I have a JSON array with various objects, and I want to show these objects in HTML using ng-repeat, but as follows:

<ul>
    <li>object 1</li>
    <li>object 2</li>
    <li>object 3</li>
    <li>object 4</li>
</ul>
<ul>
    <li>object 5</li>
    <li>object 6</li>
    <li>object 7</li>
    <li>object 8</li>
</ul>

Basically, I want to show only 4 elements per line (ul) How can I do this?

Thank!

+4
source share
4 answers

You can use limitTo filter

ng-repeat="item in items | limitTo:4"

UPDATE: This should work

<ul ng-repeat="item in arr" ng-if="$index%4==0">
  <li ng-repeat="item in arr|limitTo:4:$index" >
    {{item}} 
  </li>
</ul>

Plnkr

+4
source

Try this sample in your controller:

var list = {'1','2','3','4','5','6','7','8','9','10','11','12','13','14','15'};

// Using lodash
var chunkedList = _.chunk(list, 4);

In your HTML:

<ul ng-repeat="items in chunkedList">
 <li ng-repeat="item in items">Object {{item}}</li>
</ul>
+2
source

, :

<ul ng-repeat="n in getNumber(number)">
        <li ng-repeat="item in items | limitTo:4:n*4">object 1</li>
</ul>

JS

$scope.number = Math.round(items.length/4);
scope.getNumber = function(num) {
    return new Array(num);   
}
+1

, , ng-repeat .

, , .

.

HTML

<body ng-app="myApp" ng-controller="MainCtrl as ctrl">
  <ul ng-repeat-start="chunk in ctrl.chunkList">
    <li ng-repeat="item in chunk">{{item}}</li>
  </ul>
  <hr ng-repeat-end/>
</body>

JS

angular
  .module('myApp', [])
  .controller('MainCtrl', [function() {
    var self = this;
    var listLength;
    var groupNum;
    var i;

    self.list = [
      'item1', 'item2', 'item3', 'item4', 'item5', 
      'item6', 'item7', 'item8'
    ];

    listLength = self.list.length;
    groupNum = (listLength % 4 === 0)? listLength / 4 : Math.ceil(listLength / 4);

    self.chunkList = [];
    for (i = 0; i < groupNum; i++) {
      self.chunkList[i] = self.list.slice(i * 4, (i + 1) * 4);
    }

  }]);

Also note that if you do not need other elements of the cycle, you can just delete ng-repeat-startand ng-repeat-endinstead to use it ng-repeat.

<body ng-app="myApp" ng-controller="MainCtrl as ctrl">
  <ul ng-repeat="chunk in ctrl.chunkList">
    <li ng-repeat="item in chunk">{{item}}</li>
  </ul>
</body>

Notes

This approach is similar to @Shivas Jayram , but without a library underscore.

+1
source

Source: https://habr.com/ru/post/1584687/


All Articles