简体   繁体   English

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

[英]AngularJS - ng-init directive nested into ng-repeat directive

I need to create an array based in the following features: 我需要基于以下功能创建一个数组:

Every time the ng-repeat directive list an object the init() function automatically sends these parameter to the controller in order to get an object. 每次ng-repeat指令列出一个对象时,init()函数都会自动将这些参数发送给控制器以获取对象。

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

In the other side, the init() function receive these parameter and then returns an object. 另一方面,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!")})
}

My question is, how can I create an array based on all these objects? 我的问题是,如何基于所有这些对象创建数组?

Instead of using ng-init on each ng-repeat element, you could easily loop through users object and call ajax for each user and collect all publications together. 不必在每个ng-repeat元素上使用ng-init,而是可以轻松地遍历users对象并为每个用户调用ajax并将所有出版物收集在一起。

For that you need to use $q API's .when & .all method to wait till all promises get resolved. 为此,您需要使用$q API的.when.all方法来等待所有诺言得到解决。

Code

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM