问题描述
控制器:
$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!");
});
}
表中的data-ng-repeat指令:
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>
逻辑如下:
- 列出每个团队后,init()函数会将对象发送给控制器.
- 另一方面,init()函数将向ID团队进行查询,以获取其各自的领导者.
- 该函数将返回一个对象,第二个ng-repeat指令会将其列出到其各自的团队对象中.
但是正如我所展示的,该列表是错误的,因为每个团队中都列出了一个相同的对象.
But as I showed the list is wrong because one same object is listed in every team.
我当时想为每个对象在init()函数中创建一个数组,但我不知道如何将每个对象连接起来以创建数组.
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.
有什么建议吗?
推荐答案
我认为您只是在每个请求中更新 $ scope.leader
值,所以在 $ scope末尾.领导者
对于所有团队都将具有相同的价值.试试这个.
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>
或者您可以在第二个ng-repeat中使用函数return Leaders数组,例如:
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>
这篇关于AngularJS-使用两个对象的嵌套ng-repeat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!