我需要在Javascript中创建智能对象/函数以与我的AngularJS应用程序一起使用。我应该用什么模式呢?我目前正在使用我研究过的通用JavaScript“模块”模式,但我想知道我是否应该以AngularJS方式对这些对象/函数进行建模(下面)。也许是'服务'?
我来自Java背景,这让我有点不舒服,用辅助方法调用一个'服务'对象。但我可能需要调整我对JavaScript / AngularJS的定义。
该应用是一个基本的评分系统。两个主要对象/功能如下:
LessonScoreCard
/*
* LessonScoreCard
*
* Is a "module" that keeps track of the score a user has for a given lesson
* and whether or not for a given question there are more correct answers
* that can be made.
*/
var lessonScoreCard = (function() {
//Map of questions to scores
var privateQuestionNumberToScoreMap = {};
//API to be used by external clients
var publicAPI = {
//A public function utilizing privates
setScore: function(questionNumber, score) {
privateQuestionNumberToScoreMap[ questionNumber ] = score;
},
//Sum the total score
getTotalScore: function( ){
var totalScore = 0;
for( var questionNumber in privateQuestionNumberToScoreMap ){
totalScore += privateQuestionNumberToScoreMap[questionNumber];
}
}
};
return publicAPI;
})();
回答键
/*
* AnswerKey
*
* Is a "module" that takes an answer key and performs functions
* related to it.
*/
var answerKey = (function() {
//Set of right answers
var privateQuestionNumberToAnswerArrayMap;
//API to be used by external clients
var publicAPI = {
setAnswerKey: function(answerKeyModel) {
privateQuestionNumberToAnswerArrayMap = answerKeyModel;
},
// A public function utilizing privates
isCorrect: function(question, answer) {
var isCorrect = false;
var answerArray = privateQuestionNumberToAnswerArrayMap[ question ];
if (answerArray.indexOf(answer) !== -1) {
isCorrect = true;
}
return isCorrect;
},
getAnswerCount: function( question ){
var answerArray = privateQuestionNumberToAnswerArrayMap[ question ];
return answerArray.length;
}
};
return publicAPI;
})();
示例JSON答案密钥模型
{
1: [1, 3],
2: [4]
}
答案 0 :(得分:2)
aet是对的,但我会进一步扩展服务的角色。在Angular上构建应用程序时,服务和指令是您的两个主要构建块。
指令与视图紧密耦合。它们适用于:
服务与视图非常解耦。他们是为了:
因此,只要该事物与视图无关,服务就可以真正做到或成为任何事物。我认为您应该将您的lessonScoreCard和answerKey模块编写为服务工厂,并将它们注入任何需要访问其功能的指令。