Angular ng-repeat 条件包装元素中的项目(在 ng-repeat 中分组项目) [英] Angular ng-repeat conditional wrap items in element (group items in ng-repeat)
问题描述
我正在尝试使用条件对 ng-repeat 中的项目进行分组.
示例条件是将具有相同小时的所有元素分组.
数据:
<预><代码>[{名称:'AAA',时间:'12:05'},{名称:'BBB',时间:'12:10'},{名称:'CCC',时间:'13:20'},{名称:'DDD',时间:'13:30'},{名称:'EEE',时间:'13:40'},...]'time' 字段实际上是一个时间戳 (1399372207),但使用确切时间示例输出更容易理解.
我使用 ng-repeat 列出这些项目:
<p>{{r.name}}</p>
也尝试过:
<div ng-repeat-start="r in data| orderBy:sort:direction"></div><p>{{r.name}}</p><div ng-repeat-end></div>
有效的输出是:
<div><p>AAA</p></div><div><p>BBB</p></div><div class="group-class"><div><p>CCC</p></div><div><p>DDD</p></div><div><p>EEE</p></div>
如果我的问题没有简单的解决方案,我的最后一个选择是将数据分组,然后将其分配给 ng-repeat 中使用的范围变量.
有什么想法吗?
您可以使用 angular.filter 的 groupBy 过滤器模块.
所以你可以做这样的事情:
用法: collection |groupBy:property
使用带点符号的嵌套属性:property.nested_property
JS:
$scope.players = [{名称:'基因',团队:'阿尔法'},{名称:'乔治',团队:'测试版'},{名称:'史蒂夫',团队:'伽玛'},{名称:'宝拉',团队:'测试版'},{名称:'Scruath',团队:'伽玛'}];
HTML:
组名:{{ key }}<li ng-repeat="球员价值">玩家:{{玩家名称}}
结果:
组名:alpha
* 玩家:基因
组名:beta
* 球员:乔治
* 玩家:宝拉
组名:伽马
* 球员:史蒂夫
* 玩家:斯克鲁斯
更新: jsbin
I'm trying to group the items in a ng-repeat using a condition.
An example condition is to group all elements with the same hour.
The data:
[
{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'},
...
]
The 'time' field is actually a timestamp (1399372207) but with the exact time the example output is easier to understand.
I am listing these items using ng-repeat:
<div ng-repeat="r in data| orderBy:sort:direction">
<p>{{r.name}}</p>
</div>
also tried with:
<div ng-repeat-start="r in data| orderBy:sort:direction"></div>
<p>{{r.name}}</p>
<div ng-repeat-end></div>
A valid output is:
<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>
My last option if there isn't a simple solution for my problem would be to group the data and then assign it to the scope variable used in ng-repeat.
Any thoughts?
You can use groupBy filter of angular.filter module.
so you can do something like this:
usage: collection | groupBy:property
use nested property with dot notation: property.nested_property
JS:
$scope.players = [
{name: 'Gene', team: 'alpha'},
{name: 'George', team: 'beta'},
{name: 'Steve', team: 'gamma'},
{name: 'Paula', team: 'beta'},
{name: 'Scruath', team: 'gamma'}
];
HTML:
<ul ng-repeat="(key, value) in players | groupBy: 'team'">
Group name: {{ key }}
<li ng-repeat="player in value">
player: {{ player.name }}
</li>
</ul>
RESULT:
Group name: alpha
* player: Gene
Group name: beta
* player: George
* player: Paula
Group name: gamma
* player: Steve
* player: Scruath
UPDATE: jsbin
这篇关于Angular ng-repeat 条件包装元素中的项目(在 ng-repeat 中分组项目)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!