AngularJS - ng-init指令嵌套在ng-repeat指令中

时间:2016-06-20 20:03:09

标签: javascript arrays angularjs

我需要创建一个基于以下功能的数组:

每次ng-repeat指令列出一个对象时,init()函数会自动将这些参数发送给控制器以获取对象。

<div data-ng-repeat="user in users" data-ng-init="init(user.id)">

另一方面,init()函数接收这些参数,然后返回一个对象。

// Suppose I have 5 parameters in order to get 5 publications
$scope.init = function(id){
    $http.get("getPublicationByID/"+id)
    .success(function(data, status, headers, config){
         // Here is the object that I need to create an array
         $scope.publication = data; }) 
    .error(function(data, status, headers, config){
        $log.error("Error!")})
}

我的问题是,如何基于所有这些对象创建数组?

1 个答案:

答案 0 :(得分:1)

不是在每个ng-repeat元素上使用ng-init,而是可以轻松遍历用户对象并为每个用户调用ajax并一起收集所有出版物。

为此,您需要使用$q API的.when&amp;等待所有承诺得到解决的.all方法。

<强>代码

getAllPublications function(){
    var promiseArray = [];
    $scope.publications = []
    angular.forEach($scope.users, function(user){
       promiseArray.push($q.when($http.get("getPublicationByID/"+user.id)));
    })
    $q.all(promiseArray).then(function(response){
       $scope.publications = response; //response is array of all publications
    })
}