mcbjam mcbjam - 1 month ago 9
AngularJS Question

File pick with Angular JS

I would like to pick up a file with AngularJS:

HTML:

<div ng-controller="TopMenuCtrl">
<button class="btn" ng-click="isCollapsed = !isCollapsed">Toggle collapse</button>
<input type="file" ng-model="filepick" ng-change="pickimg()" multiple />
<output id="list"></output>
</div>


javascript:

angular.module('plunker', ['ui.bootstrap']);
function TopMenuCtrl($scope) {
$scope.pickimg = function() {
alert('a');
};
}


How can I bind the input file
onchange
action on the AngularJS
pickimg
function?
And how can i manipulate the files uploaded after?

Answer

Angular doesn't yet support ng-change for input[type=file] so you have to roll onchange implementation yourself.

First, in the HTML, define Javascript for onchange as follows:

<input ng-model="photo"
       onchange="angular.element(this).scope().file_changed(this)"
       type="file" accept="image/*" />

And then in your Angular controller code, define the function:

$scope.file_changed = function(element) {

     $scope.$apply(function(scope) {
         var photofile = element.files[0];
         var reader = new FileReader();
         reader.onload = function(e) {
            // handle onload
         };
         reader.readAsDataURL(photofile);
     });
};