ng-model不能使用文件输入 [英] ng-model not working with file input
问题描述
我试图获取文件输入的值,并将其显示在输入之外的其他位置。我在应用程序中使用了AngularJS v1.4.8。
< input type =fileng-model =fileName />
< div> {{fileName}}< / div>
这种方法适用于type =text,但不适用于type =file p>
为什么会这样,我该如何解决这个问题?
谢谢! $ b $由于我的任务非常简单,我决定采取另一种方式: / p>
< input type =filefile-input =files/>
< ul>
< li ng-repeat =文件中的文件> {{file.name}}< / li>
< / ul>
js:
< $ c $ .directive('fileInput',['$ parse',function($ parse){
return {
restrict:'A',
link:function(scope,元素,属性){
element.bind('change',function(){
$ parse(attributes.fileInput)
.assign(scope,element [0] .files)
scope。$ apply()
});
}
};
}]);
这实际上是一个解决方案,来自这个教程。请注意,这也可以用于多个文件。
然而,Serghinho的替代方案并没有什么不好,我想这只是一种更简单的方法。
I'm trying to get the value of file input and display it somewhere else, outside of the input. I'm using AngularJS v1.4.8 in the app.
<input type="file" ng-model="fileName" />
<div>{{fileName}}</div>
This approach works fine with type="text" but not with type="file".
Why is it so and how can I solve this problem?
Thank you!
Since my task was pretty straightforward, I decided to go another way:
html:
<input type="file" file-input="files" />
<ul>
<li ng-repeat="file in files">{{file.name}}</li>
</ul>
js:
.directive('fileInput', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function (scope, element, attributes) {
element.bind('change', function () {
$parse(attributes.fileInput)
.assign(scope,element[0].files)
scope.$apply()
});
}
};
}]);
This is actually a solution from this tutorial. Note that this can also work with multiple files.
Nevertheless there is nothing bad with Serghinho's alternative, there is just an easier way, I think.
这篇关于ng-model不能使用文件输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!