Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

I tried to use ng-model on input tag with type file:

<input type="file" ng-model="vm.uploadme" />

But after selecting a file, in controller, $scope.vm.uploadme is still undefined.

How do I get the selected file in my controller?

1 Answer

0 votes
by (106k points)

To get the selected file in my controller you can create a workaround with the directive as follows:-

.directive("fileread", [function () { 

return { 

scope: { 

fileread: "=" 

}, 

link: function (scope, element, attributes) { 

element.bind("change", function (changeEvent) { 

var reader = new FileReader(); 

reader.onload = function (loadEvent) { 

scope.$apply(function () { 

scope.fileread =  loadEvent.target.result; 

});

 

reader.readAsDataURL(changeEvent.target.files[0]);

        }); 

     } 

   } 

}]);

And the input tag becomes:

<input type="file" fileread="vm.uploadme" />

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...