This input element accepts a filename, which may only be programmatically set to the empty string
30,406
Ok, first of all here is a working jsFiddle.
Seems like angular didn't like that you change the attribute which is also the directive, the "file-select" attribute.
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
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.
Author by
Ramzy Abourafeh
Updated on July 23, 2020Comments
-
Ramzy Abourafeh almost 4 years
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:
<div file-select="content" path="url" class="hide"></div>
When I read a file, I got the following exception from the
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?