0

I have object which contains question and list of choices. I'm display this object on the page using nested ng-repeats. When I'm trying to change 'question' everything changes just fine, but when I'm trying to change 'choice' nothing happens. Where is the problem?

My page:

<div class="panel">

<div class="row">

    <div class="large-12 columns">

        <h3>{{ title }}</h3>

            <ol>
                <li ng-repeat="q in quiz">
                    <input type="text" ng-model="q.question">
                    <ul class="remove-li-dots">
                        <li ng-model="choice" ng-repeat="choice in q.choices">
                            <input type="text" ng-model="choice" name="answer{{ q.id }}" >
                        </li>
                    </ul>
                    </br>
                </li>
            </ol>
            <a class="button" ng-click="submitQuiz()">Submit</a><br>
            {{ quiz }}
    </div>

</div>

Screenshot of the page:

https://www.dropbox.com/s/i52fwq1os0cvcr9/repeat.png?dl=0

2
  • i think you need to put "q.choices" in {{ }} Commented Dec 1, 2014 at 14:15
  • @Bhojendra - C-Link Nepal how to do it in the right way? Commented Dec 1, 2014 at 14:21

1 Answer 1

1

Problem is that choice is a string, so when you are changing it in child scope it is changing only in child scope.

To fix this - reference it by index in array ng-repeat="(choiceIndex,choice) in q.choices,ng-model="q.choices[choiceIndex]".

Also to prevent inputs from loosing focus when changing items - you will need to add track by $index in ng-repeat directive.

<ol> <li ng-repeat="q in quiz"> <input type="text" ng-model="q.question"> <ul class="remove-li-dots"> <li ng-model="choice" ng-repeat="(choiceIndex,choice) in q.choices track by choiceIndex"> <input type="text" ng-model="q.choices[choiceIndex]" name="answer{{ q.id }}"> </li> </ul> </li> </ol>

working example: http://plnkr.co/edit/GJacjkzfT4FpfC6szsNk?p=preview


For better understanding how angular scopes works, I recommend reading this: https://github.com/angular/angular.js/wiki/Understanding-Scopes

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

2 Comments

updated an answer for case when using dictionary instead of array, or using filters to arrange items(using $index for this purpose, was incorrect)
Thanks a lot for a detailed answer! I'm new to js and angular seems to me a bit confusing

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.