简体   繁体   中英

How to dynamically generate form fields with angular?

I have an array containing a list of my backend fields for some model

ie:

$scope.fields = ['username', 'password', 'email', ...];

How can I do the following with angular:

<div ng-repeat="field in fields">
   <div class="form-group">
        <label class="col-sm-2 control-label">{{field }} </label>
        <div class="col-sm-10">
              <input class="form-control" 
                     type="text" 
                     required
                     ng-model="new_entry.{{field}}"/>
        </div>
    </div>
</div>

You should be able to set the model like this:

ng-model="new_entry[field]"

Just as you can access any object property using [] syntax:

If you have

x = { name: 'Joe', age: 24 }

You can access a property by doing

x.name

Or by doing

x['name']

http://jsfiddle.net/WN2dc/1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM