AngularJS:将ng-model绑定到input [type = file]会引发’不再可用’异常

前端之家收集整理的这篇文章主要介绍了AngularJS:将ng-model绑定到input [type = file]会引发’不再可用’异常前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
使用此代码

<!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>

会引发这个错误

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

一旦将type =“file”更改为type =“text”,错误就会消失.知道怎么解决这个问题吗?我将编写一个指令,即使在输入上也会监听更改,上传给定文件并将其值分配给绑定模型.但我这个错误阻止了我这样做.最近几天花了我很多头发.对此事的任何意见都将不胜感激.

解决方法

对于单个输入我只是使用

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

然后我可以访问我的控制器函数中的fileList并将其发送到fileReader,例如

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

我把它扩展为ng-repeat的情况,所以你可以查看这个plunker

猜你在找的Angularjs相关文章