Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying files list using AngularJS and input[type=file]

I'm trying to display a list of files which the user selects using 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);
    }
}]);

From some reason the list never gets updated.

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

Any ideas?

Thanks!

like image 734
lsxliron Avatar asked Sep 28 '22 05:09

lsxliron


1 Answers

You don't need $scope.$apply()

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

Your codes are looking very nice. and it's should be working if you did my below thing.

But you have missed only one thing. but that's main thing.

I think you may be got this below error

Uncaught Error: [$injector:modulerr] Failed to instantiate module myApp due to: Error: [$injector:nomod] Module 'myApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

please verify in your browser console window, if you got this error,then Please try this

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

instead of

app = angular.module('myApp');

You have missed empty sub models in main model('myApp',[]);

All other codes looks well.

Update :

Please see this fiddler Demo , Now your selected files names are displayed when you click print button.

like image 93
Ramesh Rajendran Avatar answered Oct 05 '22 07:10

Ramesh Rajendran