J. Doe
J. Doe

Reputation: 65

Bind ng-repeat object variable to variable in HTML

I would like some help on this issue please.

I have a form called testForm with an ng-repeat="question in questions". question has a QuestionId. In this form, I am trying to apply validation. Due to questions being dynamic, I'm not able to use static names for input fields, therefore I apply question.QuestionId to every field as name to make it unique.

Now the validation requires I do a check on the name of the field. So for example check on testForm + name of the field (QuestionId). I've tried a couple of different methods, but I do not know how I add question.QuestionId to testForm.

The code:

<div ng-form="testForm" novalidate>
  <div ng-repeat="question in questions">
    <label class="item item-input" ng-class="{ 'has-error': testForm.question.QuestionId.$error }">
        <input  class="form-error border" 
                type="text" 
                ng-model="childName" 
                name="{{question.QuestionId}}" 
                ng-minlength="2" 
                ng-maxlength="99" 
                ng-required="true">
    </label>
  </div>
  <div ng-show="testForm.question.QuestionId.$error"> asd </div>
</div>

I am trying to make the validation work, but the ng-show will look for a variable question in testForm. How do I turn question.QuestionId into text first, then put it to testForm?

Upvotes: 2

Views: 51

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136184

question.QuestionId creates formField inside testForm object. And afterwards you could retrieve formField by its key from testForm form object.

ng-show="testForm[myQuestionId].$error"

Note: You can't get question item outside ng-repeat, so better you can pass particular questionId in testForm object to get particular formField.

Upvotes: 3

Related Questions