wilson wilson - 5 months ago 30
AngularJS Question

AngularJS - Nested ng-repeat using two objects

enter image description here

Controller:

$scope.init = function(team){
$http.get("/getLeaderByTeamID/"+team.id)
.success(function (data, status, headers, config) {
// this is the object that I need to list in the table
$scope.leader = data;
})
.error(function (data, status, header, config) {
$log.error("Error!");
});


}

The data-ng-repeat directives in the table:

<table>
<thead>
<tr>
<th>Team</th>
<th>Leader</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="team in teams" data-ng-init="init(team)">
<td>{{team.name}}</td>
<td data-ng-repeat="l in leader">{{l.name}}</td>
</tr>
</tbody>




The logic is as follow:


  • When every team is listed the init() function will send the object to the controller.

  • In the other side the init() function will make a query with the ID team in order to get its respective leader.

  • The function will return one object and the second ng-repeat directive will list this into its respective team object.



But as I showed the list is wrong because one same object is listed in every team.

I was thinking create an array into the init() function with every object but I don't know how to concatenate every object in order to create an array.

Any suggestions?

Answer

I think you'r just updating $scope.leader value in every request ,so at the end $scope.leader will have the same value for all teams. try this.

$scope.init = function(teamId){
$http.get("/getLeaderByTeamID/"+teamId)
.success(function (data, status, headers, config) {
    // this is the object that I need to list in the table
    $scope.leader[teamId] = data;
})
.error(function (data, status, header, config) {
    $log.error("Error!");
});



<table>
<thead>
    <tr>
        <th>Team</th>
        <th>Leader</th>
    </tr>
</thead>
<tbody>
     <tr data-ng-repeat="team in teams" data-ng-init="init(team.id)">
        <td>{{team.name}}</td>
        <td data-ng-repeat="l in leader[team.id]">{{l.name}}</td>
     </tr>
</tbody>  

or you can use function return leaders array in the second ng-repeat like:

<td data-ng-repeat="l in getLeader(team.id)">{{l.name}}</td>