Dynamic file input – teaching html some new tricks
My page consists of divs which loop and repeat the contents of my model:
Each div will have an input field containing an unique id and the button passes the model “item” and the file contents from the input field with the unique id.
It was pretty difficult use third party module for this use case since most of them use jquery to identify the input tag id, which of course, was provided dynamically by Angular. And so I ventured to create my own widget:
What we have here is two input fields: one that is actually used to store the file value is hidden from view using “display: none” and the second input field is used to display file name to the user. The output of this markup looks like:
The first function “resetval( )” is pretty self explanatory, it simply finds the element with id matching the regular expression “fileprefix” and “filenamecontainer” followed by a number and sets the value of that field to empty. The regular expression matching is important here because the number following the prefix in provided dynamically by Angular Js. So this way I was able to consume the dynamic nature of the id attributes.
The second function “copycarry( )” carries over the click action from the “Browse Files” button to the input field that will actually hold the file. The input file is hidden from view, but this function actually invokes the input field to open the file browser by emulating the click event.
The hidden input field also has “onclick” action attached to it. The “updatefield( )” function copies the file name value from the hidden input of type file to the visible input of type text which displays the file name to the user.
The function associated to the “Upload File” button is handled by Angular Js with the ngClick directive and the function is written into the controller which will retrieve the file from the hidden input field.
Thus, with what seems like a lot of patch work I was able to get it to work, but it does work smoothly and allows styling by simple twitter-bootstrap classes and without building any complicated custom directives in Angular Js to manipulate the DOM, we have taught a new trick to plain old HTML.