Listing files using AngularJS and typing [type = file]

I am trying to display a list of files that the user selects with the input [type = file].

HTML

<div ng-app="myApp"> <div ng-controller="UploadFilesCtrl"> <input type="file" onchange="angular.element(this).scope().uploadFiles(this)" multiple /> <ul> <li ng-repeat="name in filenames"> {{name}} </li> </ul> <button ng-click="test()">PRINT</button> </div> </div> 

Js

 app = angular.module('myApp'); app.controller('UploadFilesCtrl', ['$scope', function($scope){ $scope.uploadFiles = function(element){ var files = element.files; var filenames=[]; for (i=0; i<files.length; i++){ filenames.push(files[i].name); } $scope.files = files; $scope.filenames = filenames; console.log(files, filenames); }; $scope.test = function(){ console.log($scope.files, $scope.filenames); } }]); 

For some reason, the list is never updated.

The filenames and files variables in $scope never updated outside the uploadFiles function (When I press the PRINT button after selecting a file, I get undefined).

Any ideas?

Thanks!

+5
source share
2 answers

Use $scope.$apply() to update $scope objects

 ... $scope.files = files; $scope.filenames = filenames; $scope.$apply(); console.log(files, filenames); ... 

Rest is working fine.

EDIT:

R. Graham is right. This is not complete evidence. You should use the directive instead. But just for working around you can check if digest is running like this:

 if ($scope.$root.$$phase != '$apply' && $scope.$root.$$phase != '$digest') { $scope.$apply(); } 

Updated fiddle : http://jsfiddle.net/Sourabh_/HB7LU/13086/

+2
source

You do not need $ scope. $ apply ()

.................................................. .................................................. .................................................. .........

Your codes look very beautiful. and it should work if you have completed my bottom thing.

But you missed only one thing. but this is the main thing.

I think you can get this error below

Error on failure: [$ injector: modulerr] Failed to create myApp module due to: Error: [$ injector: nomod] 'myApp' module is not available! You either mistakenly wrote the name of the module, or forgot to load it. If registering a module ensures that you specify the dependencies as the second argument.

please check in the browser console window if you have this error please try this

app = angular.module('myApp',[]);

instead

app = angular.module('myApp');

You missed the empty helper models in the main model ('myApp',[]);

All other codes look good.

Update:

Please check out this demo of a violinist , now your selected file names are displayed when you press the print button. A.

+2
source

All Articles