我知道我听起来可能有些混乱,所以请您让我详细说明
注意:此帖子已附上有效的POC(代码段)。
我有一个具有3个属性的对象数组
名称
名称
球队
team_rank
$scope.players = [
{name: 'Gene', team: 'alpha', team_rank: 1},
{name: 'George', team: 'beta', team_rank: 2},
{name: 'Steve', team: 'gamma', team_rank: 3},
{name: 'Paula', team: 'beta', team_rank: 2},
{name: 'Scruath', team: 'gamma', team_rank: 3}
];
通过运行POC,我得到了如下图所示的结果。
问题
我需要用球队名称显示球队的排名。请建议我该怎么办?
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.4.7/angular-filter.js"></script>
<meta name="description" content="[groupBy example]"/>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div ng-controller="MainController">
<ul ng-repeat="(key, value) in players | groupBy: 'team'">
Group name: {{ key }}
<li ng-repeat="player in value">
player: {{ player.name }}
</li>
</ul>
</div>
<footer>
<script>
angular.module('app',['angular.filter'])
.controller('MainController', function($scope) {
$scope.players = [
{name: 'Gene', team: 'alpha', team_rank: 1},
{name: 'George', team: 'beta', team_rank: 2},
{name: 'Steve', team: 'gamma', team_rank: 3},
{name: 'Paula', team: 'beta', team_rank: 2},
{name: 'Scruath', team: 'gamma', team_rank: 3}
];
});
</script>
</footer>
</body>
</html>
最佳答案
如果您确定每个玩家都具有team_rank
属性,则可以执行以下操作:
Group name: {{ key }} Rank: {{value[0].team_rank}}
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.4.7/angular-filter.js"></script>
<meta name="description" content="[groupBy example]"/>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div ng-controller="MainController">
<ul ng-repeat="(key, value) in players | groupBy: 'team'">
Group name: {{ key }} Rank: {{value[0].team_rank}}
<li ng-repeat="player in value">
player: {{ player.name }}
</li>
</ul>
</div>
<footer>
<script>
angular.module('app',['angular.filter'])
.controller('MainController', function($scope) {
$scope.players = [
{name: 'Gene', team: 'alpha', team_rank: 1},
{name: 'George', team: 'beta', team_rank: 2},
{name: 'Steve', team: 'gamma', team_rank: 3},
{name: 'Paula', team: 'beta', team_rank: 2},
{name: 'Scruath', team: 'gamma', team_rank: 3}
];
});
</script>
</footer>
</body>
</html>
关于javascript - AngularJS:angular-filter:如何用2列分组?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38280464/