控制ng-repeat迭代

时间:2017-11-07 19:53:20

标签: angularjs angularjs-ng-repeat angularjs-ng-init

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方法时呈现当前对象。

1 个答案:

答案 0 :(得分:0)

一种解决方案是将调用排入事件队列,然后在上一次调用完成时逐个调用事件

&#13;
&#13;
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);
        }
  });
 
});
&#13;
<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>
&#13;
&#13;
&#13;

注意1:我使用dummie api来获取实时数据

注2:删除$ timeout,只添加它以使示例清除

Here's一名带有示例

的傻瓜