繁体   English   中英

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

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

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

每次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!")})
}

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

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

为此,您需要使用$q API的.when.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
    })
}

暂无
暂无

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

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