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!

3
  • where is user coming from? field is not a property of user in the example you are giving so it won't work.. Commented May 8, 2015 at 21:29
  • 2
    @deolectrix Angular will create necessary missing properties if they are requested. Commented May 8, 2015 at 21:30
  • @dfsq thanks, my mistake, you learn something new every day...;) Commented May 8, 2015 at 21:34

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

4 Comments

Bracket notation is what I was looking for! Thank you!
I guess it should be ng-model="user['{{field}}']" no?
@jme11 No, inside of expression it would be literally property of the user with the key '{{field}}' and without quotes user[{{field}}] it would be exception. There is a demo in the answer, just try yourself ans check results.
Cool, didn't notice the demo before, but it makes sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.