期間更新與進步的範圍,我寫了一個角的工廠,負責處理上傳到S3:角工廠:上傳
'use strict';
angular.module('myApp.s3', [])
.factory('S3', function ($q) {
var aws = { ... }
var progress = 0;
function getFileName(fileURI) {
return fileURI.split('/').pop();
}
return {
progress: progress,
upload: function (fileKey, fileURI, mimeType) {
var fileName = getFileName(fileURI);
if (fileName === '') {
console.log('File name can\'t be empty');
return;
}
var defer = $q.defer();
defer.promise.then(function (event) {
alert(JSON.stringify(event));
console.log(event);
}, function (error) {
alert(JSON.stringify(error));
console.log(error);
});
var fileTransfer = new FileTransfer();
var fileUploadOptions = new FileUploadOptions();
fileUploadOptions.fileKey = 'file';
fileUploadOptions.fileName = fileName;
fileUploadOptions.chunkedMode = false;
fileUploadOptions.params = {
'key': fileKey,
'AWSAccessKeyId': aws.access_key_id,
'acl': aws.acl,
'policy': aws.policy,
'signature': aws.signature
};
fileTransfer.upload(fileURI, encodeURI('https://' + aws.bucket + '.s3.amazonaws.com/'),
defer.resolve, defer.reject, fileUploadOptions);
fileTransfer.onprogress = function (progressEvent) {
if (progressEvent.lengthComputable) {
progress = (progressEvent.loaded/progressEvent.total) * 100;
console.log(progress);
} else {
//loadingStatus.increment();
}
};
return defer.promise();
}
};
});
此代碼工作正常,文件被上傳到S3。進度日誌也在起作用。當我在控制器中使用此工廠並將進度綁定到作用域時,我沒有在範圍內看到進度更新。我想這是由於範圍沒有得到更新事件。
我見過一個解決方法,其中工廠使用範圍初始化,而scope.apply()在工廠內調用。我不認爲這是在Angular中這樣做的正確方法,但我也不知道正確的方式。有小費嗎?
是的!我剛發現這是可能的,我認爲它更好!謝謝! –