AngularJS ng-repeat rows / ul

时间:2015-04-26 02:15:59

标签: javascript angularjs angularjs-ng-repeat

我有一个包含各种对象的JSON数组,我想使用ng-repeat在HTML中显示这些对象,但如下所示:

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

基本上我想每行只显示4个项目(ul) 我怎么能这样做?

谢谢!

4 个答案:

答案 0 :(得分:4)

您可以使用过滤器limitTo

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

更新:这应该有效

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

Plnkr

答案 1 :(得分:2)

在你的控制器中试试这个样本:

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

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

在您的HTML中:

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

答案 2 :(得分:1)

没试过,试试看:

<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);   
}

答案 3 :(得分:1)

基本思想是将数组块化为多维数组,然后使用嵌套结构将其ng-repeat两次。

如果您想更改块号,可以将其更改为您喜欢的任何整数。

Live demo就在这里。

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);
    }

  }]);

另请注意,如果您不需要循环中的其他元素,则只需删除ng-repeat-startng-repeat-end,然后直接使用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>

注释

此方法类似于@Shivas Jayram,但不需要underscore库。