Yasser B.
Yasser B.

Reputation: 835

How to use two lists in ng-repeat Angular

I'm using the awesome framework angular js. I'm facing a tiny problem.

I'm using two lists I'm not really sure if we can do something similar to this

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

and then

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

my json looks like :

{
"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"
}
]
}

I want to show something similar to this :

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

Thanks for giving me the answer to the first problem, and in the same time i'm using order by how can I order the second team as well.

Upvotes: 0

Views: 3773

Answers (2)

Shomz
Shomz

Reputation: 37701

Since you're not going each vs each, but in pairs, this will work:

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

And since there is the equal number of players in each team, a single ng-repeat will work (just to get the $index):

ng-repeat ="player1 in team1"

See it here:

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);
})
<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>

Upvotes: 3

rwisch45
rwisch45

Reputation: 3702

You could just combine your teams into one array. Doing that would allow for variable numbers of teams and players.

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

Then bind to the allPlayers array in your HTML

Upvotes: 0

Related Questions