gpt4 book ai didi

javascript - 使用 AngularJS 和输入 [type=file] 显示文件列表

转载 作者:搜寻专家 更新时间:2023-11-01 04:16:17 24 4
gpt4 key购买 nike

我正在尝试显示用户使用输入 [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);
}
}]);

由于某种原因,列表永远不会更新。

$scope 中的 filenamesfiles 变量永远不会在 uploadFiles 函数之外更新(当选择文件后单击打印按钮,我得到未定义)。

有什么想法吗?

谢谢!

最佳答案

你不需要 $scope.$apply()

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

您的代码看起来非常不错。如果你做了我下面的事情,它应该会起作用。

但是你只漏掉了一件事。但这是主要的事情。

我想你可能遇到了下面的错误

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.

请在您的浏览器控制台窗口中验证,如果出现此错误,请尝试此操作

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

代替

app = angular.module('myApp');

您在主模型中遗漏了空子模型('myApp',[]);

所有其他代码看起来都不错。

更新:

请看这个fiddler Demo , 现在您选择的文件名会在您点击打印按钮时显示出来。

关于javascript - 使用 AngularJS 和输入 [type=file] 显示文件列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29765012/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com