我正在尝试在 angularjs 中构建多项选择题(MCQ)应用程序。我有以下数据。
var questions = [
{
questionId: 1,
question: 'Can I build this app with angular',
answer: 'yes',
options: ['yes','no','depends','may be']
},
{
questionId: 2,
question: 'Is earth is flat',
answer: 'no',
options: ['yes','no','don\'t know']
}
]
我的index.html看起来像这样
<div data-ng-repeat="question in questions">
<p>question: {{ question.question }}</p>
<div data-ng-repeat="option in question.options">
<label data-ng-class="{correct-ans: answer[$parent.question.questionId][$index] == $parent.question.answer}">
<input type="radio" data-ng-model="answer[$parent.question.questionId][$index]" name="{{ 'option'+$parent.question.questionId }}" value="{{ option }}"/>{{ option }}
</label>
</div>
</div>
当用户选择正确答案时,我想将 css 类 Correct-ans 应用到标签。上面的代码抛出TypeError无法将“某个值”设置为未定义。 然后我尝试定义一个 $scope 变量 $scope.answer = [[],[]],但现在它仅适用于第一个问题,只有在 TypeError 再次出现之后。请帮助我如何做到这一点。提前致谢。
最佳答案
出现类型错误是因为 ng-model 尝试将某些内容设置为 $scope.answer[questionId][optionId] 并且未定义。当您定义 $scope.answer = [[],[]] 时,它仅适用于第一个问题,因为它的 QuestionId == 1,并且 $scope.answer 1指答案数组的第二元素(因为数组索引从0开始)。对于第二个问题,它尝试访问不存在的 $scope.answer[2]。
我不确定您是否真的需要这里的二维数组 - 您需要的是存储用户对每个问题的回答,与有效答案进行比较,并突出显示相应的选项(如果选择了该选项)。我建议使用以下代码:
//javascript
$scope.answer = [];
$scope.isCorrectAnswer = function(question, option) {
return option == question.answer && $scope.answer[question.questionId] == option;
}
//html
<div data-ng-repeat="option in question.options">
<label data-ng-class="{'correct-ans': isCorrectAnswer(question, option)}">
<input type="radio" data-ng-model="answer[question.questionId]" name="{{ 'option'+question.questionId }}" value="{{ option }}"/>{{ option }}
</label>
</div>
这是jsfiddle .
关于javascript - 二维数组作为 ngmodel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21355173/