5

I am working on an angular project where I need to create a form based on an array of questions. I would like to create ng-model for each question in the array.

So I have come up with something like the following, but it is not working.

<div class="form-group" data-ng-repeat="question in questions">
    <label for="{{question.label}}" class="col-md-2 control-label">
        {{question.label}}:
    </label>
    <div class="col-md-10">
        <input type="text" 
               class="form-control" 
               name="{{question.label}}" 
               data-ng-model={{question.label}}
               required />
        <span class="error"
              data-ng-show="formQuickView.{{question.label}}.$error.required">
            Required!
        </span>
    </div>
</div>                   

Could someone help me out for this one ?
Thanks heaps in advance.

gkalpak
  • 47,844
  • 8
  • 105
  • 118
loveNZ
  • 307
  • 2
  • 12

2 Answers2

7
formQuickView[question.label].$error.required

This is regular JavaScript syntax. You want to access the property of formQuickView with the name defined by question.label.

Update

Somehow I missed the main point, the ng-modelexpression. Basically you do the same thing here. You have two choices (technically only one):

  • Add an object to your scope, say questions, then use questions[question.label].
  • When you have a form, then give it a name and an object is added automatically. E.g. <form name="questions" .... and the same as above.
a better oliver
  • 26,330
  • 2
  • 58
  • 66
  • Thanks for that, but my main problem is ng-model. Can I create a model like with {{expression}} at all? – loveNZ Jan 11 '14 at 11:02
4

ng-model does not work with {{}} it considers the string passed to it as an expression referencing a scope property.

I'm not sure if I understand your code correctly. In your code, I think data-ng-model="question.label" should work.

If you want to reference a dynamic field specified in your label field. Try this with your ng-model:

<input type="text" ng-model="question[question.label]"/>

DEMO

Khanh TO
  • 48,509
  • 13
  • 99
  • 115
  • Thanks I got it work with something like this ng-model="question.value", then on the save it loop through all my question objects' value property to get values. – loveNZ Jan 11 '14 at 11:26
  • @loveNZ: my statement about `data-ng-model="question.label"` works? – Khanh TO Jan 11 '14 at 11:28