我正在使用工厂函数在Angular和Im中构建一个测验来加载问题数据库。
angular
.module('myQuiz')
.factory('QuestionService', ['$http', '$q', function($http, $q) {
var currentQuestion = 0;
return {
getQuestion: function() {
var def = $q.defer();
$http.get("quizdb.json")
.success(function(data) {
// resolve the data by returning the question, choices and correctanswer in an object
def.resolve({
totalQuestions: data.allQuestions.length,
question: data.allQuestions[currentQuestion].question,
choices: data.allQuestions[currentQuestion].choices,
correctAnswer: data.allQuestions[currentQuestion].correctAnswer
});
})
.error(function() {
def.reject("failed to retrieve questions");
});
return def.promise;
},
getCurrentQuestion: function() {
return currentQuestion;
},
nextQuestion: function() {
(currentQuestion >= 0) ? currentQuestion += 1 : false;
},
prevQuestion: function() {
(currentQuestion < 0) ? false : currentQuestion -= 1;
}
};
}]);
当用户点击&#34; next&#34;按钮它将在此工厂中调用nextQuestion。这在工厂中正确更新,但我不知道如何在我的控制器中获取最新值。我不认为$ watch会工作,超时功能似乎有点黑客。也许最好使用值服务来保存currentQuestion变量?
另外一个问题,我应该将问题逻辑保留在当前工厂中还是更好地创建一个单独的工厂?
答案 0 :(得分:0)
为什么不能只是致电getCurrentQuestion()
来提出问题,或者如果您需要一步完成所有操作,只需从nextQuestion
返回当前问题。
getCurrentQuestion: function() {
return currentQuestion;
},
nextQuestion: function() {
(currentQuestion >= 0) ? currentQuestion += 1 : false;
return curretQuestion;
},