[英]AngularJS nested ng-repeat
I have object which contains question and list of choices. 我有包含问题和选项列表的对象。 I'm display this object on the page using nested ng-repeats.
我使用嵌套的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 https://www.dropbox.com/s/i52fwq1os0cvcr9/repeat.png?dl=0
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]"
. 要解决此问题,请通过
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. 另外,为防止更改项目时输入失去焦点-您将需要在ng-repeat指令中
track by $index
添加track by $index
。
<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 工作示例: 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 为了更好地了解角度范围的工作原理,我建议阅读以下内容: https : //github.com/angular/angular.js/wiki/Understanding-Scopes
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.