0

I am trying to iterate over array of questions. But I need to attach radio button answers to each question. In this case I need to add different ng-models for each answer. I tried the code below but it didn't work.

Is this the correct way of using $index of the ng-repeat?

<li class="fields" ng-repeat="question in questions">
    <p>question:{{question.title}}</p>
    <div class="radio-buttons">
        <input type="radio" id="radio01" value="0" ng-model="answer[$index]" checked="checked"/>
        <label for="radio01"><span></span>Yes</label>
        <input type="radio" id="radio02" value="1" ng-model="answer[$index]"/>
        <label for="radio02"><span></span>No</label>
    </div>
</li>
1
  • What doesn't work? This looks like it should put all answers (0/1) in an answer array. Or maybe you want ng-model="question.answer"? Commented Mar 7, 2017 at 11:47

2 Answers 2

2

you need to do it like this modelname{{$index}}

 <li class="fields" ng-repeat="question in questions">
        <p>question:{{question.title}}</p>
        <div class="radio-buttons">
            <input type="radio" id="radio01" value="0" ng-model="answer{{$index}}" checked="checked"/>
            <label for="radio01"><span></span>Yes</label>
            <input type="radio" id="radio02" value="1" ng-model="answer{{$index}}"/>
            <label for="radio02"><span></span>No</label>
        </div>
    </li>
Sign up to request clarification or add additional context in comments.

1 Comment

dont forget to accept the answer if it works :D @ahmdabos
0

You can also do it via square bracket notation too if that pleases you aesthetically more:

<li class="fields" ng-repeat="(i, question) in questions">
  <p>question:{{question.title}}</p>
  <div class="radio-buttons">
    <input type="radio" id="radio01" value="0" ng-model="answer[i]" checked="checked"/>
    <label for="radio01"><span></span>Yes</label>
    <input type="radio" id="radio02" value="1" ng-model="answer[i]"/>
    <label for="radio02"><span></span>No</label>
  </div>
</li>

Also to note, models are better when expressed as dot models. So for example:

<input type="radio" ng-model="answer[i]" />

Would be better as:

<input type="radio" ng-model="models.answer[i]" />

Then in your controller this makes it simple to list all the models via the object 'models', rather than finding out how many answer[i] models there are.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.