Ng model does not work with file input

I am trying to get the input value of a file and display it somewhere else, outside of the input. I am using AngularJS v1.4.8 in the application.

<input type="file" ng-model="fileName" /> <div>{{fileName}}</div> 

This approach works fine with type = "text", but not with type = "file".

Why is this and how can I solve this problem?

Thanks!

+5
source share
1 answer

Since my task was quite simple, I decided to go the other way:

HTML:

  <input type="file" file-input="files" /> <ul> <li ng-repeat="file in files">{{file.name}}</li> </ul> 

JS:

 .directive('fileInput', ['$parse', function ($parse) { return { restrict: 'A', link: function (scope, element, attributes) { element.bind('change', function () { $parse(attributes.fileInput) .assign(scope,element[0].files) scope.$apply() }); } }; }]); 

This is actually a solution from this tutorial. Please note that this may also work with multiple files.

However, there is nothing wrong with Serginho's alternative, I think there is an easier way.

+8
source

Source: https://habr.com/ru/post/1241599/


All Articles