I have a directive like below. It's supposed to load a file from an <input type=file>
and set it to an ng-model
provided. It's also got some custom validation only incidental to my question. It's also on plunkr.
What's wrong is that the ngModel never gets set at all. It's always undefined
. Why?
app.directive('fileInput', function () {
var link = function (scope, element, attrs, ngModel) {
var VALIDTYPES = ['text/csv', 'text/directory', 'text/vcard'];
var updateModel = function () {
var file = element[0].files[0];
if (file) {
scope.$apply(function () {
if (VALIDTYPES.indexOf(file.type) >= 0) {
ngModel.$setValidity("mimetype", true);
ngModel.$setViewValue(file);
} else {
ngModel.$setValidity("mimetype", false);
alert("Sorry, can only accept VCF and CSV files.");
}
})
}
};
element.bind('change', updateModel);
};
return {
restrict: 'A',
require: 'ngModel',
template: "<input type='file'>",
replace: true,
link: link,
scope: {},
}
});