Directive to get files input with ng-model
(multiple files)
The AngularJS built-in <input>
directive does not handle <input type=file>
. One needs a custom directive for that.
<input type="file" files-input ng-model="fileArray" multiple>
The files-input
directive:
angular.module("app").directive("filesInput", function() {
return {
require: "ngModel",
link: function postLink(scope,elem,attrs,ngModel) {
elem.on("change", function(e) {
var files = elem[0].files;
ngModel.$setViewValue(files);
})
}
}
})
The above directive adds a change listener that updates the model with the files property of the input
element.
This directive enables <input type=file>
to automatically work with the ng-change
and ng-form
directives.
The DEMO on PLNKR
Inline Demo of files-input
Directive
angular.module("app",[]);
angular.module("app").directive("filesInput", function() {
return {
require: "ngModel",
link: function postLink(scope,elem,attrs,ngModel) {
elem.on("change", function(e) {
var files = elem[0].files;
ngModel.$setViewValue(files);
})
}
}
});
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app">
<h1>AngularJS Input `type=file` Demo</h1>
<input type="file" files-input ng-model="fileArray" multiple>
<h2>Files</h2>
<div ng-repeat="file in fileArray">
{{file.name}}
</div>
</body>