Angular.js Dynamic Form Input Types
I am trying to create an Angular.js app that creates dynamic inputs from a JSON object.
So first, I have a JSON object (called fields):
[
{"field_id":209,"form_id":1,"name":"firstname","label":"First Name","type":"text"},
{"field_id":210,"form_id":1,"name":"lastname","label":"Last Name","type":"text"},
{"field_id":211,"form_id":1,"name":"email","label":"Email","type":"text"},
{"field_id":212,"form_id":1,"name":"picture","label":"Picture","type":"file"},
{"field_id":213,"form_id":1,"name":"address","label":"Address","type":"file"},
{"field_id":214,"form_id":1,"name":"password","label":"Password","type":"password"},
{"field_id":215,"form_id":1,"name":"","label":"","type":"submit"}
]
The object key type
is the input type for the form. See below:
<p ng-repeat="field in fields">
{{field.name}} : <input type="{{field.type}}" value="{{record.data[field.name]}}" />
</p>
Now it works fine for the fields submit
, text
, password
, checkbox
and radio
. But if type file
, it sets the input type text
.
If I replace {{field.name}}
with {{field.type}}
for text, I can confirm what it outputs file
.
If I statically change <input type="{{field.type}}"...
to <input type="file"...
, it displays the input file correctly.
Why doesn't it let me set the input type as a file dynamically?
source to share
Topic if property change type
if item <input>
is a hot topic.
Actually, since the behavior of AngularJS depends on whether jQuery was added (before or after angular.js).
You can read some discussion about changeable heretype
:
change the type of an input field with jQuery
There is also a pull request for AngularUI to add a new directive with dynamic type change support: https://github.com/angular-ui/angular-ui/pull/371
If you find the suggested solution not good enough (though, since the type hasn't changed after the form is rendered), you can go with ng-switch
way - just show the input file to the user.
source to share