簡體   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