Here is a JSON example that I have:
fields: [
{
name: "my_field_name",
type: "text",
placeholder: "place holder text"
}],
I aim to dynamically generate form controls based on the field type and assign them an ng-model value equal to their name.
This is my approach for generating these fields:
<div ng-repeat="field in fields">
<div ng-if="field.type=='text'" class="form-group">
<label class="control-label">{{field.name}}</label>
<input type="{{ field.type }}"
ng-model="{{ field.name }}"
class="form-control"
required
placeholder="{{ field.placeholder }}"
/>
</div> ....other types
In this scenario, the generated output should be like this:
<div ng-repeat="field in fields">
<div ng-if="field.type=='text'" class="form-group">
<label class="control-label">my_field_name</label>
<input type="text"
ng-model="my_field_name"
class="form-control"
required
placeholder="{{ field.placeholder }}"
/>
</div>
However, the ng-model attribute does not recognize the {{}} syntax and results in an error.
Syntax Error: Token '{' invalid key at column 2 of the expression [{{ field.name }}] starting at [{ field.name }}]
Is there a way to resolve this issue?
EDIT:: I found a solution! By utilizing the $index variable provided by ng-repeat, I was able to create unique identifiers without any conflicts. Special thanks to: AngularJS - ng-repeat to assign/generate a new unique ID