我是一个与Angular JS挣扎的新手。
我正在尝试进行问卷调查并提供以下代码,但无论我尝试什么,都会不断收到错误的反馈。
我为四个按钮中的每一个分配了一个数值,其标题是从数组中提取的。我想根据数组中的正确答案检查所选按钮的值。有人能告诉我哪里出错了吗?
HTML
<div id="ansblock">
<button type="button" ng-click="myAnswer=0">{{options [0]}} </button>
<button type="button" ng-click="myAnswer=1">{{options [1]}}</button>
<button type="button" ng-click="myAnswer=2">{{options [2]}}</button>
<button type="button" ng-click="myAnswer=3">{{options [3]}}</button>
<p>Test to show button click value working {{myAnswer}}</p>
</div>
<button ng-click="checkAnswer()">Submit</button>
<span ng-show="correctAns">That is correct!</span>
<span ng-show="!correctAns">Sorry, that is an incorrect answer.</span>
JS:
var app = angular.module('quizApp', []);
app.directive('quiz', function (quizFactory) {
return {
restrict: 'AE',
scope: {},
templateUrl: 'template.html',
link: function (scope, elem, attrs) {
scope.start = function () {
scope.id = 0;
scope.quizOver = false;
scope.inProgress = true;
scope.getQuestion();
};
scope.reset = function () {
scope.inProgress = false;
scope.score = 0;
}
scope.getQuestion = function () {
var q = quizFactory.getQuestion(scope.id);
if (q) {
scope.question = q.question;
scope.options = q.options;
scope.answer = q.answer;
scope.answerMode = true;
} else {
scope.quizOver = true;
}
};
scope.checkAnswer = function () {
var ans = $('scope.myAnswer').val();
if(ans==scope.options[scope.answer]) {
scope.score++;
scope.correctAns = true;
} else {
scope.correctAns = false;
}
scope.answerMode = false;
};
scope.nextQuestion = function () {
scope.id++;
scope.getQuestion();
}
scope.reset();
}
}
});
app.factory('quizFactory', function () {
var questions = [
{
question: "Which of the following is a WW2 fighter?",
options: ["Albatross", "Concorde", "Spitfire", "Mirage"],
answer: 2
},
{
question: "When was the Great Fire of London?",
options: ["1666", "1966", "1844", "1235"],
answer: 0
},
{
question: "Which group is a Swedish pop band?",
options: ["Eagles", "Led Zeppelin", "Beatles", "Abba"],
answer: 3
},
{
question: "Which city is the capita of Australia?",
options: ["Canberra", "Sydney", "Melbourne", "Hobart"],
answer: 0
},
{
question: "Which brand does not make motorcycles?",
options: ["BMW", "Mercedes", "Kawasaki", "Honda"],
answer: 1
}
];
return {
getQuestion: function (id) {
if (id < questions.length) {
return questions[id];
} else {
return false;
}
}
};
});