期间更新与进步的范围,我写了一个角的工厂,负责处理上传到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中这样做的正确方法,但我也不知道正确的方式。有小费吗?
是的!我刚发现这是可能的,我认为它更好!谢谢! –