0

Here is my sample JSON

fields: [
        {
          name: "my_field_name",
          type: "text",
          placeholder: "place holder text"
        }],

What I want to do is, dynamically generate form controls depending on the type field and give them ng-model field value as name.

This is how I am generating 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

So in this case my generated value should look like

<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>

But this ng-model attribute does not resolve {{}} and I get an error

Syntax Error: Token '{' invalid key at column 2 of the expression [{{ field.name }}] starting at [{ field.name }}]

Is there any way to resolve this?

EDIT:: I figured out! YEY! so there is $index field predefiend in ng-repeat. I could safely use it to create unique ids. thanks to: AngularJS - ng-repeat to assign/generate a new unique ID

user1079065
  • 1,717
  • 5
  • 27
  • 46

2 Answers2

0

Don't use interpolation braces {{}} for ng-model. it should point to a property variable

ng-model="field.name"
charlietfl
  • 164,229
  • 13
  • 110
  • 143
  • ten ng-model is field.name. I want it to be my_field_name – user1079065 Jan 09 '18 at 04:23
  • Then you need custom directives. Can't use `{{}}` in `ng-model` so you will need to compile the input yourself. Might want to take a look at other dynamic form modules like angular-formly – charlietfl Jan 09 '18 at 04:29
0

Try using without interpolation for ng-model

<input type="{{ field.type }}" ng-model="field.name" class="form-control" required placeholder="{{ field.placeholder }}"
Sajeetharan
  • 186,121
  • 54
  • 283
  • 331