ng-model not working with file input

20,125

Since my task was pretty straightforward, I decided to go another 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. Note that this can also work with multiple files.

Nevertheless there is nothing bad with Serghinho's alternative, there is just an easier way, I think.

Share:
20,125
Mitya Ustinov
Author by

Mitya Ustinov

Updated on February 10, 2020

Comments

  • Mitya Ustinov
    Mitya Ustinov about 4 years

    I'm trying to get the value of file input and display it somewhere else, outside of the input. I'm using AngularJS v1.4.8 in the app.

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

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

    Why is it so and how can I solve this problem?

    Thank you!

  • Adarsh Singh
    Adarsh Singh almost 5 years
    How to get its buffer data and type of file ?