除了上面接受的答案外,我还使用underscore.js库创建了一个通用的“ groupBy”过滤器。
JSFiddle(更新):http :
//jsfiddle.net/TD7t3/
过滤器
app.filter('groupBy', function() {
return _.memoize(function(items, field) {
return _.groupBy(items, field);
}
);
});
注意“记忆”调用。此下划线方法会缓存函数的结果,并每次都停止对角度表达式进行求值,从而防止角度达到摘要迭代限制。
HTML
<ul>
<li ng-repeat="(team, players) in teamPlayers | groupBy:'team'">
{{team}}
<ul>
<li ng-repeat="player in players">
{{player.name}}
</li>
</ul>
</li>
</ul>
我们将'groupBy'过滤器应用于'team'属性的teamPlayers范围变量。我们的ng-repeat接收(key,values [])的组合,可在以下迭代中使用。
2014年6月11日更新,
我按过滤器扩展了分组,以考虑使用表达式作为键(例如嵌套变量)。角度解析服务对此非常方便:
过滤器(支持表达式)
app.filter('groupBy', function($parse) {
return _.memoize(function(items, field) {
var getter = $parse(field);
return _.groupBy(items, function(item) {
return getter(item);
});
});
});
控制器(带有嵌套对象)
app.controller('homeCtrl', function($scope) {
var teamAlpha = {name: 'team alpha'};
var teamBeta = {name: 'team beta'};
var teamGamma = {name: 'team gamma'};
$scope.teamPlayers = [{name: 'Gene', team: teamAlpha},
{name: 'George', team: teamBeta},
{name: 'Steve', team: teamGamma},
{name: 'Paula', team: teamBeta},
{name: 'Scruath of the 5th sector', team: teamGamma}];
});
html(带有sortBy表达式)
<li ng-repeat="(team, players) in teamPlayers | groupBy:'team.name'">
{{team}}
<ul>
<li ng-repeat="player in players">
{{player.name}}
</li>
</ul>
</li>
JSFiddle:http :
//jsfiddle.net/k7fgB/2/