I'm using this directive for uploading files. The file has a label that comes a long with it. I have a function I call before I try to upload and if that function returns false then I don't want to do the upload because they user didn't give a label value.
The issue seems to be when I just return from the element.on('change') callback it never gets called again. When I return $.ajax() when everything works the element.on('change') gets triggered as many times as I want. So I'm not sure why just calling return stops element.on('change') from triggering in future upload tries.
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);
});
}
}
}
}]);