I\'m writing an web app with AngularJS and angular-material. The problem is that there\'s no built-in component for file input in angular-material. (I feel that file uploading d
File uploader with AngularJs Material and a mime type validation:
Directive:
function apsUploadFile() {
var directive = {
restrict: 'E',
require:['ngModel', 'apsUploadFile'],
transclude: true,
scope: {
label: '@',
mimeType: '@',
},
templateUrl: '/build/html/aps-file-upload.html',
controllerAs: 'ctrl',
controller: function($scope) {
var self = this;
this.model = null;
this.setModel = function(ngModel) {
this.$error = ngModel.$error;
ngModel.$render = function() {
self.model = ngModel.$viewValue;
};
$scope.$watch('ctrl.model', function(newval) {
ngModel.$setViewValue(newval);
});
};
},
link: apsUploadFileLink
};
return directive;
}
function apsUploadFileLink(scope, element, attrs, controllers) {
var ngModelCtrl = controllers[0];
var apsUploadFile = controllers[1];
apsUploadFile.inputname = attrs.name;
apsUploadFile.setModel(ngModelCtrl);
var reg;
attrs.$observe('mimeType', function(value) {
var accept = value.replace(/,/g,'|');
reg = new RegExp(accept, "i");
ngModelCtrl.$validate();
});
ngModelCtrl.$validators.mimetype = function(modelValue, viewValue) {
if(modelValue.data == null){
return apsUploadFile.valid = true;
}
if(modelValue.type.match(reg)){
return apsUploadFile.valid = true;
}else{
return apsUploadFile.valid = false;
}
};
var input = $(element[0].querySelector('#fileInput'));
var button = $(element[0].querySelector('#uploadButton'));
var textInput = $(element[0].querySelector('#textInput'));
if (input.length && button.length && textInput.length) {
button.click(function(e) {
input.click();
});
textInput.click(function(e) {
input.click();
});
}
input.on('change', function(e) {
//scope.fileLoaded(e);
var files = e.target.files;
if (files[0]) {
ngModelCtrl.$viewValue.filename = scope.filename = files[0].name;
ngModelCtrl.$viewValue.type = files[0].type;
ngModelCtrl.$viewValue.size = files[0].size;
var fileReader = new FileReader();
fileReader.onload = function () {
ngModelCtrl.$viewValue.data = fileReader.result;
ngModelCtrl.$validate();
};
fileReader.readAsDataURL(files[0]);
ngModelCtrl.$render();
} else {
ngModelCtrl.$viewValue = null;
}
scope.$apply();
});
}
app.directive('apsUploadFile', apsUploadFile);
html template:
cloud_upload
Exemple: