问题:我有一个数据列表,每个记录都有一个ID,用于进行API调用以获取有关此特定项目的更多信息。问题是 - ng-repeat已经循环遍历我的数据。如何为每个ng-repeat操作传递不同的API调用响应?
代码:
查看:
<div ng-repeat="activity in userActivity">
<div class="row">
<div class="col-md-10 col-md-offset-2">
<a href="#">{[ user.fullname ]}</a> has {[ activity.action ]} to: <a href="#"> {[ post.post ]}<br>
</div>
</div>
角度控制器:
profileApp.controller('mainController', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams){
$scope.user = [];
$scope.userActivity = [];
$scope.post = [];
$http.get('/api/user', {params: { id: $routeParams.id }})
.success(function(res){
$scope.user = res.user;
$scope.userActivity = res.user.activity;
$http.get('/api/post', {params: { postID: $scope.userActivity[0].post }})
.success(function(res){
$scope.post = res.post;
})
.error(function(data, status){
console.log(data);
});
})
.error(function(data, status){
console.log(data);
});
}]);
响应中的/ api / user活动如下所示:
"activity": [
{
"post": "123456781",
"action": "agreed"
},
{
"post": "123456782",
"action": "disagreed"
}
]
那么有人可以帮助并指出正确的方向,如何将数据与ng-view一起填充?目前,它只是显示了123456781的post.post,这是有道理的,但如何将这些变量传递给ng-repeat?
提前致谢
答案 0 :(得分:1)
res.user.activity
是数组,
首先循环遍历$scope.userActivity
数组,然后为数组中的每个值创建api call
,然后使用新密钥$scope.userActivity
更新post_obj
数组是您将在视图中使用的响应。
然后,您的控制器应更改为,
profileApp.controller('mainController', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams){
$scope.user = [];
$scope.userActivity = [];
$scope.post = [];
$http.get('/api/user', {params: { id: $routeParams.id }})
.success(function(res){
$scope.user = res.user;
$scope.userActivity = res.user.activity;
for(var i=0 ; i < $scope.userActivity.length ; i++)
{
$http.get('/api/post', {params: { postID: $scope.userActivity[i].post }})
.success(function(res){
$scope.userActivity[i].post_obj = res.post;
})
.error(function(data, status){
console.log(data);
});
}
})
.error(function(data, status){
console.log(data);
});
}]);
然后,您的视图应更改为,
<div ng-repeat="activity in userActivity">
<div class="row">
<div class="col-md-10 col-md-offset-2">
<a href="#">{{ user.fullname }}</a> has {{ activity.action }} to: <a href="#"> {{ activity.post_obj }}<br>
</div>
</div
</div>
此userActivity数组现在包含我们在每个帖子对应的响应中获得的post_obj
答案 1 :(得分:1)
ng-repeat="activity in userActivity" ng-click="myFunction(activity)"
在控制器中创建myFunction,只获取点击的活动。