javascript - Dynamic ng-model binding ng-repeat loop in AngularJS - Stack Overflow

admin2025-04-26  2

I have a following collection of fields.

$scope.fields = ['name','postcode','phone'];

I need to have input controls dynamically generated as many as the fields above. So a fixed version of below

<div class="col-sm-3" ng-repeat="user in users">
    <div ng-repeat="field in fields">
        <input class="form-control" ng-model="user.field" /> <!-- .field isn't resolving -->
    </div>
</div>

would hopefully generate something like below...

<div class="col-sm-3" ng-repeat="user in users">
    <div><input class="form-control" ng-model="user.name" /></div>
    <div><input class="form-control" ng-model="user.postcode" /></div>
    <div><input class="form-control" ng-model="user.phone" /></div>
</div>

Any ideas? Thanks!

I have a following collection of fields.

$scope.fields = ['name','postcode','phone'];

I need to have input controls dynamically generated as many as the fields above. So a fixed version of below

<div class="col-sm-3" ng-repeat="user in users">
    <div ng-repeat="field in fields">
        <input class="form-control" ng-model="user.field" /> <!-- .field isn't resolving -->
    </div>
</div>

would hopefully generate something like below...

<div class="col-sm-3" ng-repeat="user in users">
    <div><input class="form-control" ng-model="user.name" /></div>
    <div><input class="form-control" ng-model="user.postcode" /></div>
    <div><input class="form-control" ng-model="user.phone" /></div>
</div>

Any ideas? Thanks!

Share Improve this question asked May 8, 2015 at 21:26 DocZDocZ 1792 silver badges10 bronze badges 3
  • where is user ing from? field is not a property of user in the example you are giving so it won't work.. – deowk Commented May 8, 2015 at 21:29
  • 2 @deolectrix Angular will create necessary missing properties if they are requested. – dfsq Commented May 8, 2015 at 21:30
  • @dfsq thanks, my mistake, you learn something new every day...;) – deowk Commented May 8, 2015 at 21:34
Add a ment  | 

1 Answer 1

Reset to default 6

You need to use bracket notation to access variable object property:

<div class="col-sm-3" ng-repeat="user in users">
    <div ng-repeat="field in fields">
        <input class="form-control" ng-model="user[field]" />
    </div>
</div>

Demo: http://plnkr.co/edit/fkCYr4k0RwizxsOS9HhC?p=preview

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745647549a311969.html

最新回复(0)