jQuery 这个输入元素接受一个文件名,它只能以编程方式设置为空字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27718644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
This input element accepts a filename, which may only be programmatically set to the empty string
提问by Ramzy Abourafeh
I found the following directive to read a file:
我找到了以下指令来读取文件:
.directive('fileSelect', function() {
var template = '<input type="file" id="files" class="hide"/>';
return function(scope, elem, attrs) {
var selector = $(template);
elem.append(selector);
selector.bind('change', function(changeEvent) {
var reader = new FileReader();
reader.onloadend = function(loadEvent) {
scope.$apply(function() {
if (loadEvent && loadEvent.target && loadEvent.target.result)
scope[attrs.fileSelect] = loadEvent.target.result;
if (changeEvent && changeEvent.target && changeEvent.target.files && changeEvent.target.files.length > 0)
scope[attrs.path] = changeEvent.target.files[0].name;
});
};
if (changeEvent && changeEvent.target &&
changeEvent.target.files && changeEvent.target.files.length > 0)
reader.readAsText(changeEvent.target.files[0]);
});
scope.$watch(attrs.fileSelect, function(file) {
selector.val(file);
});
};
});
I put in the html the following element:
我在 html 中添加了以下元素:
<div file-select="content" path="url" class="hide"></div>
When I read a file, I got the following exception from the selector.val(file);
:
当我读取文件时,我从以下文件中得到以下异常selector.val(file);
:
Error: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string.
Can anyone help me?
谁能帮我?
回答by Yair Tavor
Ok, first of all here is a working jsFiddle.
好的,首先这里是一个可用的 jsFiddle。
Seems like angular didn't like that you change the attribute which is also the directive, the "file-select" attribute.
似乎 angular 不喜欢您更改属性,该属性也是指令,即“文件选择”属性。
By taking it out to a different attribute ('content' attribute in my example) we avoid the problem.
通过将其取出到不同的属性(在我的示例中为“内容”属性),我们避免了这个问题。
In line 15 of the script I changed
在脚本的第 15 行中,我更改了
scope[attrs.fileSelect] = loadEvent.target.result;
To
到
scope[attrs.content] = loadEvent.target.result;
You then need to provide the 'content' attribute in the directive call, like this:
然后,您需要在指令调用中提供“内容”属性,如下所示:
<div file-select content="content" path="url" class="hide"></div>
I happen to run into similar problems in the past when trying to save some space in my html, so I just avoid it and prefer declaring these types of directives with element restriction.
过去,当我试图在我的 html 中节省一些空间时,我碰巧遇到了类似的问题,所以我只是避免它并更喜欢用元素限制声明这些类型的指令。
回答by Nikhil Mahirrao
Just try this
试试这个
scope.$watch(attrs.fileSelect, function(file) {
if(!file)
{
selector.val('');
}
});