我有一个上传功能,它会循环遍历所选的文件并将它们添加到服务器文件系统中。
上传功能:
$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
函数已经完成?
$scope.uploadImages()
将永远不会以你期望的方式返回值。你需要在.success
或.error
回调期间调用另一个函数。 - g.d.d.c