I am facing an issue with my two directives. One directive is responsible for checking the file size, while the other ensures that the uploaded file format is valid. When both directives are assigned to an input=file
element separately, they work fine. However, when used together, the validFileSize directive seems to interfere with the selectNgValidationFiles directive.
//view
<input type="file" name="uploadedDocs" id="uploadedDocs" data-ng-model="fileStore.file" select-ng-validation-files valid-file-size multiple>
//controller
function validFileSize($parse){
return {
require: 'ngModel',
restrict: 'A',
link: function(scope, el, attrs, ngModel) {
var model = $parse(attrs.ngModel);
var modelSetter = model.assign;
var maxSize = 2000; //2000 B
el.bind('change', function() {
scope.$apply(function() {
scope.fileStore.maxSizeError = false;
if (el[0].files.length > 1) {
modelSetter(scope, el[0].files);
} else {
modelSetter(scope, el[0].files[0]);
}
if(el[0].files.length > 0) {
var fileSize = el[0].files[0].size;
if (fileSize === 0) {
scope.fileStore.maxSizeError = true;
}
}
});
});
}
}
}
function selectNgValidationFiles() { //if files to be uploaded vary in future, add condition to check type or create new directive
return {
require: "ngModel",
link: function postLink(scope,elem,attrs,ngModel) {
var validFormats = ['pdf', 'PDF', 'doc', 'DOC', 'docx', 'DOCX', 'jpg', 'JPG', 'jpeg', 'JPEG','png', 'PNG', 'gif', 'GIF', 'pptx', 'PPTX', 'csv', 'CSV', 'xlsx', 'XLSX', 'zip', 'ZIP'];
elem.bind('change', function () {
validFile(false);
scope.$apply(function () {
ngModel.$render();
});
});
ngModel.$render = function () {
console.log('elem : ',elem)
ngModel.$setViewValue(elem[0].files[0]);
};
function validFile(bool) {
ngModel.$setValidity('pdfIncorrect', bool);
}
ngModel.$parsers.push(function(value) {
var ext = value.name.substr(value.name.lastIndexOf('.')+1);
if(ext=='') return;
if(validFormats.indexOf(ext) == -1){
console.log('not valid format')
return value;
}
validFile(true);
return value;
});
}
}
};
query
What could be causing conflict between my directives? It seems like one directive might be overriding the other, but I'm unsure how to resolve this issue.