元素中的角度ng-repeat条件包装项目(ng-repeat中的组项目)

我正在尝试使用条件将项目分组为ng-repeat。


一个示例条件是将所有元素分组为同一小时。


数据:


[

    {name: 'AAA', time: '12:05'},

    {name: 'BBB', time: '12:10'},

    {name: 'CCC', time: '13:20'},

    {name: 'DDD', time: '13:30'},

    {name: 'EEE', time: '13:40'},

    ...

]

“时间”字段实际上是一个时间戳记(1399372207),但是使用准确的时间,示例输出将更易于理解。


我正在使用ng-repeat列出这些项目:


<div ng-repeat="r in data| orderBy:sort:direction">

   <p>{{r.name}}</p>

</div>

还尝试了:


<div ng-repeat-start="r in data| orderBy:sort:direction"></div>

    <p>{{r.name}}</p>

<div ng-repeat-end></div>

有效输出为:


<div class="group-class">

    <div><p>AAA</p></div>

    <div><p>BBB</p></div>

</div>

<div class="group-class">

    <div><p>CCC</p></div>

    <div><p>DDD</p></div>

    <div><p>EEE</p></div>

</div>

如果没有针对我的问题的简单解决方案,我的最后一个选择是将数据分组,然后将其分配给ng-repeat中使用的作用域变量。


有什么想法吗?


繁华开满天机
浏览 577回答 3
3回答

一只斗牛犬

首先在控制器中建立组:&nbsp;$scope.getGroups = function () {&nbsp; &nbsp; var groupArray = [];&nbsp; &nbsp; angular.forEach($scope.data, function (item, idx) {&nbsp; &nbsp; &nbsp; &nbsp; if (groupArray.indexOf(parseInt(item.time)) == -1) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; groupArray.push(parseInt(item.time));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; &nbsp; return groupArray.sort();};然后为其过滤:&nbsp;myApp.filter('groupby', function(){&nbsp; &nbsp; return function(items,group){&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;return items.filter(function(element, index, array) {&nbsp; &nbsp; &nbsp; &nbsp; return parseInt(element.time)==group;&nbsp; &nbsp; &nbsp; &nbsp;});&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp;}) ;&nbsp;然后更改模板:&nbsp;<div ng-repeat='group in getGroups()'>&nbsp; &nbsp; &nbsp;<div ng-repeat="r in data | groupby:group" class="group-class">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<div><p>{{r.name}}</p></div>&nbsp; &nbsp; &nbsp;</div>&nbsp;</div>查看演示
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

AngularJS