0

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>

1 Answer 1

1

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

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

7 Comments

So angular assigns the output of a input field to whatever you place into ng-model? It would seem that the only magic that happens is the first step of creating x.
Yes, angular assigns the output of a input field to whatever you place into ng-model. The magic is that you can also change x in the javascript, and the input field updates automatically too. It's two way data-binding, instead of one way.
Can you create a fiddle of the above. I don't think it works as you expect it to.
Fiddle added to answer
Sorry it does work: jsfiddle.net/WN2dc/4. I must be doing something else wrong.
|

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.