刚刚开始在Angular.js中遇到了一个小小的打嗝,这个打嗝花了很长时间才弄明白。我有3组4个单选按钮。我正在尝试访问用户在每组中选择的单选按钮。问题是到目前为止我只能用一套来做。如果有多个设置,在用户选择一个单选按钮后,所有设置都会切换到所选的单选按钮。我很确定它与我的ng-model =“$ parent.selected”有关,但我不知道如何修复它。
由于某些原因,我无法让Angular使用JSFiddle,所以这就是我所拥有的:
HTML:
<form name="myForm" ng-controller="testController">
<div ng-repeat="question in questions | limitTo:3">
<div>{{question.Question}}</div>
<input type="radio" ng-model="$parent.selected" value="A" name="{{question.id}}" />{{question.A}}<br />
<input type="radio" ng-model="$parent.selected" value="B" name="{{question.id}}" />{{question.B}}<br />
<input type="radio" ng-model="$parent.selected" value="C" name="{{question.id}}" />{{question.C}}<br />
<input type="radio" ng-model="$parent.selected" value="D" name="{{question.id}}" />{{question.D}}<br />
Selected = {{selected}}
</div>
</form>
JS:
angular.module('nodeServerApp')
.controller('testController', function ($scope) {
$scope.questions =
[
{
"id": 0,
"Question": "Is C the right answer?",
"A": "This is choice A.",
"B": "This is choice B.",
"C": "This is choice C.",
"D": "This is choice D.",
"Answer": "C"
},
{
"id": 1,
"Question": "Is A the right answer?",
"A": "This is choice A.",
"B": "This is choice B.",
"C": "This is choice C.",
"D": "This is choice D.",
"Answer": "A"
},
{
"id": 2,
"Question": "Is D the right answer?",
"A": "This is choice A.",
"B": "This is choice B.",
"C": "This is choice C.",
"D": "This is choice D.",
"Answer": "D"
}
];
});
答案 0 :(得分:2)
ngModel
应该是selected
,而不是$parent.selected
(所有问题都会分享)......
<input type="radio" ng-model="selected" value="A" name="{{question.id}}" />{{question.A}}<br />
<input type="radio" ng-model="selected" value="B" name="{{question.id}}" />{{question.B}}<br />
<input type="radio" ng-model="selected" value="C" name="{{question.id}}" />{{question.C}}<br />
<input type="radio" ng-model="selected" value="D" name="{{question.id}}" />{{question.D}}<br />
Selected = {{selected}}
另请考虑将selected
放在question
上,以便所有内容都放在一个地方......
<input type="radio" ng-model="question.selected" value="A" name="{{question.id}}" />{{question.A}}<br />
<input type="radio" ng-model="question.selected" value="B" name="{{question.id}}" />{{question.B}}<br />
<input type="radio" ng-model="question.selected" value="C" name="{{question.id}}" />{{question.C}}<br />
<input type="radio" ng-model="question.selected" value="D" name="{{question.id}}" />{{question.D}}<br />
Selected = {{question.selected}} {{question.selected === question.Answer ? "Correct" : "Incorrect"}}