簡體   English   中英

控制ng-repeat迭代

[英]Controlling ng-repeat iterations

HTML:

<div ng-repeat="data in $ctrl.list">
    <div ng-init="$ctrl.applyAction(data)">
        <h4>{{data.name}}</h4>
        <ul ng-if="data.steps">
            <li ng-repeat="step in data.steps">{{step.name}}</li>
        </ul>
    </div>
</div>

控制器:

$onInit() {
    this.list = [{
        name: "First Obj"
    }, {
        name: "Second Obj"
    }, {
        name: "Third Obj"
    }, {
        name: "Fourth Obj"
    }];
}

applyAction(data) {
    this.someHttpService.getResponse(data).then(function(success) {
        data.reqForSecondServiceCall = success.data;
        this.secondServiceCall(data);
    }, function(error) {
        // console.log(error);
    });
}

secondServiceCall(data) {
    this.someHttpService.getSecondServiceResponse(data).then(function(success) {
        data.status = success.data;
    }, function(error) {
        // console.log(error);
    });
}

當前,ng-repeat將遍歷列表對象,而不管對每個對象進行的服務調用(異步)。

所需的功能是僅在對上一個對象完成了applyActions方法后才呈現當前對象。

一種解決方案是將調用排隊在事件隊列中,然后在上一次調用完成后逐個調用事件

 angular.module('myApp',[]).controller('myCtrl', function($scope, $http, $timeout){ $scope.title = 'welcome'; $scope.finishedEvent = ''; $scope.eventQueue = []; $scope.list = [{ name: "First Obj" }, { name: "Second Obj" }, { name: "Third Obj" }, { name: "Fourth Obj" }]; $scope.applyAction = function(data, index) { //declare the event var event = function(){ var testApi = "https://jsonplaceholder.typicode.com/posts"; $http.get(testApi).then(function(response) { data.steps = response.data.slice(0,2); $scope.finishedEvent = data.name; }, function(error) { console.log(error); }); }; if(index == 0){ event(); }else{ $scope.eventQueue.push(event); } }; $scope.$watch('finishedEvent', function(){ if($scope.eventQueue.length > 0){ $timeout(function(){ console.log($scope.finishedEvent + '- loaded') var event = $scope.eventQueue[0]; $scope.eventQueue.splice(0, 1); //remove current event from queue event(); }, 1000); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <body ng-app="myApp" ng-controller="myCtrl"> <h1>{{title}}</h1> <div ng-repeat="data in list"> <div ng-init="applyAction(data, $index)"> <h4>{{data.name}}</h4> <ul ng-if="data.steps"> <li ng-repeat="step in data.steps">{{step.title}}</li> </ul> </div> </div> </body> 

注意1:我使用了dummie api來獲取實時數據

注意2:刪除$ timeout,僅添加它以使示例清晰明了

這是一個例子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM