2014-02-11 59 views
2

我有一个上传功能,它循环选定的文件并将它们添加到服务器文件系统中。角度异步功能不会在继续之前完成

上传功能:

$scope.uploadImages = function() { 
     for (var i = 0; i < $scope.imageModels.length; i++) { 
      var $file = $scope.imageModels[i].file; 
      (function (index) { 
       $upload 
        .upload({ 
         url: "/api/upload/", 
         method: "POST", 
         data: { type: 'img', object: 'ship' }, 
         file: $file 
        }) 
        .progress(function (evt) { 
         $scope.imageProgress[index] = parseInt(100.0 * evt.loaded/evt.total); 
        }) 
        .success(function (data) { 
         $scope.imageProgressbar[index] = 'success'; 

         // Add returned file data to model 
         $scope.imageModels[index].Path = data.Path; 
         $scope.imageModels[index].FileType = data.FileType; 
         $scope.imageModels[index].FileSize = $scope.imageModels[index].file.size; 

         var image = { 
          Path: data.Path, 
          Description: $scope.imageModels[index].Description, 
          Photographer: $scope.imageModels[index].Photographer 
         }; 
         $scope.images.push(image); 
        }) 
        .error(function (data) { 
         $scope.imageProgressbar[index] = 'danger'; 
         $scope.imageProgress[index] = 'Upload failed'; 

         alert("error: " + data.ExceptionMessage); 
        }); 
      })(i); 
     } 
     return $scope.images; 
    } 
}; 

如果我把这个单独它工作得很好,但是当我与我的其他功能放在一起,好像它没有完成:

$scope.create = function() { 
    $scope.ship = {}; 

    // This function is asynchronous 
    $scope.ship.Images = $scope.uploadImages(); 

    // Here $scope.ship don't contain any Images 
    angular.extend($scope.ship, $scope.shipDetails); 

    shipFactory.createShip($scope.ship).success(successPostCallback).error(errorCallback); 
}; 

$scope.ship不包含图像,当我调试它开始上传它们,但不等待它完成,只是执行下一行代码。

我该如何使它工作,以确保$scope.uploadImages函数在继续之前完成?

+0

您正在使用AJAX错误。如果上传是异步的,那么'$ scope.uploadImages()'将永远不会按照您期望的方式返回一个值。您需要在'.success'或'.error'回调期间*调用另一个函数。 –

+0

http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – Moob

+0

我发现我从这篇文章的答案: http://stackoverflow.com/questions/ 18421830 /如何到等待,直到最响应来自-来自该http请求功能于angularjs – Lars

回答

相关问题