Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: binding ng-model to input[type=file] raises 'no longer usable' exception

Using this code:

<!doctype html>
<html lang="en" ng-app="app">
<head>
    <meta charset="UTF-8">
    <title>ngTest</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.3/angular.js"></script>
    <script>
        angular
            .module('app', [])
            .controller('Main', ['$scope', function($s) {
                $s.data = {
                    level1: {
                        level2: {
                            elements: [{
                                name: 'item1'
                            },{
                                name: 'item2'
                            },{
                                name: 'item3'
                            },{
                                name: 'item4'
                            }]
                        }
                    }
                };
            }]);
    </script>
</head>
<body ng-controller="Main">
    <div ng-repeat="item in data.level1.level2.elements">
        <input type="file" ng-model="item.name">
    </div>
    <pre>{{data}}</pre>
</body>

Will raise this error:

Error: An attempt was made to use an object that is not, or is no longer, usable.

Error fades as soon as you change type="file" to type="text". Any idea how to get around this? Im going to write a directive that will listen to the change even on the input, upload given file and assign it's value to bound model. But I this error prevents me doing so. Last couple of days costed me quite some hair. Any input on the matter would be much appreciated.

like image 376
Aleksandr Makov Avatar asked Nov 01 '22 11:11

Aleksandr Makov


1 Answers

For a single input I simply use

<input ng-model="file" onchange="angular.element(this).scope().upload(this)" type="file">

Then I get access to a fileList in my controllers function and send it to a fileReader e.g.

$scope.upload = function(el) {
  console.log(el.files);
};

I extended it for case of the ng-repeat, so you could check this plunker

like image 132
Qustion Avatar answered Nov 11 '22 12:11

Qustion