rahul
rahul

Reputation: 506

Ionic radio group not reflecting in model

So I'm loading a bunch of questions from an api, every question has its own set of answers.

Im unable to populate the ng-model for radio box to record the selected answer

html

<div class="list">
    <div class="item item-text-wrap" ng-repeat="question in vm.questions track by $index">
        <h2>{{question.text}}</h2>
        <ion-list if="question.type='mcq'">
          <ion-radio ng-model="vm.answers[$index].answer_text" ng-value="'{{option.text}}'" ng-repeat="option in question.options" name="vm.answers[$index].answer_text">{{option.text}}</ion-radio>
        </ion-list>
        <input type="text" ng-if="question.type=='simple'" ng-model="vm.answers[$index].answer_text" placeholder="{{question.text}}"/>
    </div>
</div>

relevalnt code from the controller

vm.answers = [];

api.need_assesment_questions.query(
    //on success
    function success(response) {
        vm.questions = response;

        //populate answers 
        for (var i = 0; i < vm.questions.length; i++) {

            vm.answers.push({ question_text: vm.questions[i].text, answer_text: '' });

        }
    },
    //on error
    function error(response) {
        alert(response.message);
    }
);

The issue im facing is that answers array always rewrites the first answer text

fiddle : http://jsfiddle.net/pn2qL/76/

Upvotes: 0

Views: 89

Answers (1)

Gaurav Kumar Singh
Gaurav Kumar Singh

Reputation: 1570

You need to initialise the question index on top and use it in your model, because there is another ng-repeat which override the previous $index

Try this

<div class="list">
    <div class="item item-text-wrap" 
            ng-repeat="question in vm.questions track by $index" 
            ng-init="qIndex = $index">
        <h2>{{question.text}}</h2>
        <ion-list if="question.type='mcq'">
            <ion-radio ng-model="vm.answers[qIndex].answer_text" ng-value="option.text" ng-repeat="option in question.options" name="{{vm.answers[qIndex].answer_text}}">{{option.text}}</ion-radio>
        </ion-list>
        <input type="text" ng-if="question.type=='simple'" ng-model="vm.answers[$index].answer_text" placeholder="{{question.text}}" />
    </div>
</div>

Working fiddle

Upvotes: 1

Related Questions