如何在ng-repeat Angular中使用两个列表

时间:2015-05-27 14:29:51

标签: javascript angularjs

我正在使用令人敬畏的框架角度js。我面临一个小问题。

我正在使用两个列表我不确定我们是否可以执行与此类似的操作

ng-repeat ="player1 in team1 | orderBy:'id'"

然后

<h3>{{player1.name}} - {{player2.name}}</h3>

我的json看起来像:

{
"team1":[
{
"name":"player1T1",
"id":"1",
"role":"goalkeeper"
},
{
"name":"player2T1",
"id":"3",
"role":"attacker"
},
  {
"name":"player3T1",
"id":"2",
"role":"midfielder"
},

],
"team2":[

{
"name":"player2T2",
"id":"3",
"role":"attacker"
},
  {
"name":"player3T2",
"id":"2",
"role":"midfielder"
},
{
"name":"player1T2",
"id":"1",
"role":"goalkeeper"
}
]
}

我想展示类似的东西:

Player1T1 (goalkeeper) - Player1T2 (goalkeeper) 
Player2T1 (attacker)   - Player2T2 (attacker)
Player3T1 (midfielder) - Player3T2 (midfielder)

感谢您给我第一个问题的答案,同时我也在使用订单,我该如何订购第二个团队。

2 个答案:

答案 0 :(得分:3)

由于你不是每个人都要对抗,而是成对出现,这样做会有效:

<h3>{{team1[$index].name}} - {{team2[$index].name}}</h3>

由于每支队伍中有相同数量的队员,所以只需要一次ng-repeat(只是为了获得$ index):

ng-repeat ="player1 in team1"

在此处查看:

&#13;
&#13;
angular.module('app', [])
.controller('Ctrl', function($scope) {
  $scope.teams = {
    "team1": [{
      "name": "player1",
      "id": "1"
    }, {
      "name": "player2",
      "id": "2"
    }],
    "team2": [{
      "name": "player4",
      "id": "4"
    }, {
      "name": "player3",
      "id": "3"
    }]
  }
  
  function sortById(a,b){return a.id > b.id}
  
  $scope.teams.team1.sort(sortById);
  $scope.teams.team2.sort(sortById);
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="Ctrl">
  <div ng-repeat="x in teams.team1">
    <h3>{{teams.team1[$index].name}} - {{teams.team2[$index].name}}</h3>
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以将您的团队合并为一个阵列。这样做可以容纳不同数量的球队和球员。

var allPlayers= [];
for(var prop in teams){
     teams[prop].forEach(function(player){
          player['team'] = prop;
          allPlayers.push(player);
     });
}

然后绑定到HTML

中的allPlayers数组