2014-02-11 57 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

回答

相關問題