【发布时间】:2019-11-21 12:54:26
【问题描述】:
我正在使用这个指令来上传文件。该文件有一个很长的标签。我在尝试上传之前调用了一个函数,如果该函数返回 false,那么我不想进行上传,因为他们的用户没有给出标签值。
问题似乎是当我刚刚从 element.on('change') 回调返回时,它再也不会被调用。当我在一切正常时返回 $.ajax() 时, element.on('change') 会被触发多次。所以我不确定为什么只是调用 return 会阻止 element.on('change') 在未来的上传尝试中触发。
angular.module('ngSimpleUpload', [])
.directive('ngSimpleUpload', ['$http', function ($http) {
return {
scope: {
webApiUrl: '@',
callbackFn: '=',
errorFn: '=',
preFn: '=',
selectedFileFn: '=',
additionalData: '=',
buttonId: '@'
},
link: function (scope, element, attrs) {
// original code, trigger upload on change
element.on('change', function (evt) {
var files = evt.__files_ || (evt.target && evt.target.files);
Upload(files);
});
function Upload(files) {
// can bail out of the entire call if preupload returns false
if (scope.preFn(scope.additionalData) == false) {
return;
}
var fd = new FormData();
angular.forEach(files, function (v, k) {
fd.append('file', files[k]);
scope.selectedFileFn(files[k].name);
});
return $.ajax({
type: 'POST',
url: scope.$eval(scope.webApiUrl),
data: fd,
async: true,
cache: false,
contentType: false,
processData: false
}).done(function (d) {
// callback function in the controller
scope.callbackFn(d, scope.additionalData);
}).fail(function (x) {
// callback function in the controller
scope.errorFn(x);
});
}
}
}
}]);
【问题讨论】:
标签: angularjs