您的位置:首页技术文章
文章详情页

angular.js - ng-repeat如何限数量输出?

【字号: 日期:2024-10-06 15:44:51浏览:35作者:猪猪

问题描述

现在碰到这样一个需求:有一个数组

$scope.items = [ {name:’a1’},{name:’a2’},{name:’a3’}....]

现在需要它输出

<ul> <li>a1</li><li>a2</li><li>a3</li><li>a4</li><li>a5</li><li>a6</li><li>a7</li><li>a8</li><li>a9</li><li>a10</li> //10个</ul><ul> <li>a11</li><li>a12</li><li>a13</li><li>a14</li><li>a15</li><li>a16</li><li>a17</li><li>a18</li><li>a19</li><li>a20</li> //10个</ul><ul> <li>a21</li><li>a22</li>... //10个</ul>

我想用ng-repeat输出,想出的方案是,先把数组 length 除以 10

$scope.n = Math.ceil ( items.length / 10 );

然后ng-repeat输出 n 个 ul,再分别在ul里 ng-repeat 10个item。

那么问题来了,如何ng-repeat输出n个ul?

<ul ng-repeat=' ...不会写... '> <li ng-repeat = ' item in items | ...//如何过滤'>{{item.name}} </li></ul>

求问各路大神啦!

更新问题!感谢各位同行!

首先,css已经不可动了,因为根据产品需求已经写好了样式,并得到了每行需要10个li的结果。看到@zchq88 这位朋友的提醒以后,我立刻做了一维数组转二维数组的过滤器,像@Chobits 同学那样的。但是报错。

Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!

angular.js - ng-repeat如何限数量输出?console.log() 会发现数组被执行了N遍过滤器。google也没有找到原因和解决方案。我猜测是,拆数组的时候,由于指引型数据,引发了重复脏检查。实验了angular.copy也失败,现在正在找其他解决方案。再次感谢!期待有同学提出其他解决方案!

解决!最后一次更新:

因为产品中items实际的结构是

$scope.group = [ {key:888,items:[ {name:’a1’},{name:’a2’},{name:’a3’}....,{name:’a13’}...//n多个] }, {key:999,items:[ {name:’a1’},{name:’a2’},{name:’a3’}....,{name:’a33’}...//n多个] }, ....]

绕开了html中加过滤器产生的重复脏检查问题。根据@Chobits 提供的过滤器,在控制器里对group进行了过滤

group.forEach(function(items){ items.items = $filter(’group’)(items.items);})

然后再ng-repeat输出,问题解决。

<p ng-repeat = 'input in group'> <ul ng-repeat='items in input.items'><li ng-repeat='item in items'> {{item.name}}</li> </ul></p>

prefect!thanks everyone!

问题解答

回答1:

//http://stackoverflow.com/a/14463190/2586541app.filter(’group’, function () { return function (items, groupSize) {var groups = [], inner;for (var i = 0; i < items.length; i++) { if (i % groupSize === 0) {inner = [];groups.push(inner); } inner.push(items[i]);}return groups; };});

$scope.group = [ {key:1,items:[ {name:’a1’},{name:’a2’},{name:’a3’}....] }, {key:2,items:[ {name:’a1’},{name:’a2’},{name:’a3’}....] }, ....]

<ul ng-repeat='g in group track by g.key'> <li ng-repeat='item in g.items'>{{item.name}} </li></ul>回答2:

http://stackoverflow.com/questions/21644493/how-to-split-the-ng-repeat-data-with-three-columns-using-bootstrap

However, the most direct and just plainly simple way to get columns is to use CSS columns:是的 赞同这个排一下版 一行显示几个完全可以用css做 方法多的都懒得写

回答3:

为什么不直接把ITEMS用JS变成2维数组?然后输出?

回答4:

把数据整理成树形结构即可。。。比如

scope.list = [{name:'a',children:[ {name:’son1 of a’}, {name:’son2 of a’} ]},{name:'b',children:[ {name:’son1 of b’}, {name:’son2 of b’} ]}]

然后ng里用双层repeat

<ul ng-repeat='item in list'> <li ng-repeat = ' son in item.children'>{{son.name}} </li></ul>

相关文章: