<li ng-repeat="questionAndAnswers in questionnaire">
<select ng-model="selectedAnswer" ng-options="answer as answer.displayText for answer in questionAndAnswers.answers track by answer.value" ng-change="validateAnswers()">
</select>
</li>
"questionAndAnswer": [{
"question": "Is your camera fully functional?",
"answers": [{
"displayText": "Yes, everything works",
"value": "Success"
}, {
"displayText": "Some of the buttons are broken",
"value": "Failure"
}]
}, {
"question": "Does your camera has any obvious damage?",
"answers": [{
"displayText": "No it's perfect",
"value": "Success"
}, {
"displayText": "Yes, there is heavy damage",
"value": "Failure"
}]
}]
我正在使用ng-options和ng-repeat基于问卷的大小(给出的json样本)创建多个下拉菜单。有人可以建议最好的角度方式来获得validateAnswers()javascript中的答案,我可以验证用户是否选择了“成功”答案。如果所有答案都是成功,我需要显示成功消息。
答案 0 :(得分:2)
我会使用$ index将答案存储在数组中,并在validateAnswer函数中验证数组。
在你的html:minor tweek中:
<li ng-repeat="questionAndAnswers in questionnaire track by $index">
{{questionAndAnswers.question}}<br>
<select ng-model="selectedAnswers[$index]" ng-options="answer.value as answer.displayText for answer in questionAndAnswers.answers" ng-change="validateAnswers()">
</select>
</li>
在您的控制器中:
$scope.questionnaire = [{
"question": "Is your camera fully functional?",
"answers": [{
"displayText": "Yes, everything works",
"value": "Success"
}, {
"displayText": "Some of the buttons are broken",
"value": "Failure"
}]
}, {
"question": "Does your camera has any obvious damage?",
"answers": [
{
"displayText": "No it's perfect",
"value": "Success"
},
{
"displayText": "Yes, there is heavy damage",
"value": "Failure"
}]
}];
$scope.selectedAnswers = [];
$scope.validateAnswers = function() {
console.log($scope.selectedAnswers);
var allSuccess = true;
for (i = 0; i < $scope.questionnaire.length; i++) {
allSuccess = allSuccess && ($scope.selectedAnswers[i] === 'Success');
}
if (allSuccess) {
$scope.result = 'Congratz! All answers correct!';
} else {
$scope.result = '';
}
}
以下是Plunker
中的工作示例就个人而言,如果你只有这两个值,我会使用布尔值作为答案的值而不是字符串'Success'和'Failure'。
希望这会帮助你。