我知道我可能听起来有些混乱,所以我请你让我详细说明
注意:此帖子附有一份正在运行的POC(一段代码)。
我有一个具有3个属性的对象数组 名称
$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>
答案 0 :(得分:2)
如果你确定每个玩家都有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>
答案 1 :(得分:1)
方法1:
<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>
方法2:
<ul ng-repeat="(key, value) in players | groupBy: '[team,team_rank]'">
Group, Rank : {{ key }}
<li ng-repeat="player in value">
player: {{ player.name }}
</li>
</ul>