AngularJS - upload and display image using FileReader API (multiple files) [duplicate] AngularJS - upload and display image using FileReader API (multiple files) [duplicate] angularjs angularjs

AngularJS - upload and display image using FileReader API (multiple files) [duplicate]


SOLUTION:

http://jsfiddle.net/orion514/kkhxsgLu/136/

:)

<div ng-controller="MyCtrl"><div ng-repeat="step in stepsModel">    <img class="thumb" ng-src="{{step}}" /></div><input type='file' ng-model-instant        onchange="angular.element(this).scope().imageUpload(event)"       multiple />

$scope.stepsModel = [];$scope.imageUpload = function(event){     var files = event.target.files; //FileList object     for (var i = 0; i < files.length; i++) {         var file = files[i];             var reader = new FileReader();             reader.onload = $scope.imageIsLoaded;              reader.readAsDataURL(file);     }}$scope.imageIsLoaded = function(e){    $scope.$apply(function() {        $scope.stepsModel.push(e.target.result);    });}


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>


Zypps987, try using var file = files[0], not inside a loop.