角度foreach后执行一个函数

时间:2016-06-19 17:35:31

标签: angularjs flow

我试图在foreach角度之后执行此操作,执行一项功能以保存在工作台上的服务器图像。

但问题是该函数在完成foreach之前执行,我返回一个空数组。

功能:

$scope.processFiles = function(images){

    if(!$rootScope.client.media) $rootScope.client.media = [];

    angular.forEach(images, function(flowFile, i){

        var fileReader = new FileReader();

        fileReader.onload = function (event) {

            var uri = event.target.result;

            $scope.image = {
                filename: uri
            };

            $rootScope.client.media.push($scope.image);

        };

        fileReader.readAsDataURL(flowFile.file);

        //$scope.saveFiles();

    });

};

$scope.saveFiles = function() {

    $rootScope.client.put({client: $rootScope.client.client})

    .then(function(res){
        $rootScope.client = res;
        toast.msgToast('Arquivos de imagens atualizados com sucesso.');
    });

};

HTML:

<md-card>

    <md-toolbar ng-show="!selectedmedia.length" class="md-table-toolbar md-default">

        <div class="md-toolbar-tools">
            <h2 class="md-title">imagens</h2>
            <div flex></div>
            <md-button class="md-icon-button" aria-label="Upload imagem" flow-btn>
                <md-icon>add</md-icon>
                <md-tooltip>Upload imagem</md-tooltip>
            </md-button>
        </div>

    </md-toolbar>

1 个答案:

答案 0 :(得分:1)

在您的情况下,您使用两个异步函数:

  • angular.forEach
  • fileReader.onload

为了找出最佳使用时间promise

jsfiddle上的示例。

&#13;
&#13;
angular.module('ExampleApp', [])
  .controller('ExampleController', function($timeout, $q) {
    var vm = this;
    vm.doneSave = false;
    vm.media = [];
    vm.startSave = function() {
      vm.media = [];
      vm.doneSave = false;
      var images = [1, 2, 3, 4, 5];
      var promises = [];
      angular.forEach(images, function(image) {
        var defer = $q.defer();
        console.log('forEach', image);
        //simulate fileReader.onload
        $timeout(function() {
          vm.media.push("saved: " + image);
          console.log('saved', image);
          // we done here. Resolve the promise
          defer.resolve(image);
        }, image * 1000);
        promises.push(defer.promise);
      });          
      $q.all(promises).then(function() {// executed, then all promises resolved
        vm.onSaved();
      }).catch(console.error);
    }
    vm.onSaved = function() {
      vm.doneSave = true;
      console.log('on saved', vm.media);
    }
  });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ExampleApp">
  <div ng-controller="ExampleController as vm">
    <form name="myForm">
      <div ng-show="vm.doneSave">
        Saving done!
      </div>
      <div ng-show="!vm.doneSave">
        Click to save!
      </div>
      <button ng-click="vm.startSave()">
        Save
      </button>
    </form>
  </div>
</div>
&#13;
&#13;
&#13;