这是我使用AngularJS的第一个项目,不幸的是,它并不是一个温和的介绍。我不得不“摔倒在地”,可以这么说。
我的任务是构建一个可自定义的调查表单,其中从DB加载问题定义。在大多数情况下,由于this angular-dynamic forms project,我设法让这项工作得以实现。我现在需要在调查问题中添加加权评分,以便调查答案可以生成总分。
我的数据结构基本如下:
[{
"title": "Survey title",
"active": true,
"form": {
"FocusQuestions": {
"type": "fieldset",
"title": "Focus area",
"scoreWeight": 30,
"fields": [{
"AgeGroup": {
"type": "select",
"label": "What is the age group?",
"options": {
"1": "Infants (0 - 2yrs)",
"2": "Toddlers (2 - 4yrs)",
"3": "Children" (4 - 13yrs)"
},
"maxScore": 3
}
}
}
}
"responses":[{
"name": "John Doe",
"answers":{
"AgeGroup": 2
}
}]
}]
在我的代码中,我有一个SurveyController负责加载调查定义等,还有一个ResponseController负责与实际调查响应相关的任务。我弄清楚的是将响应答案与调查中定义的评分权重相结合以生成分数的正确“角度方式”。因为有两个控制器需要共享数据,我怀疑我可能需要像ScoringService那样完成所有计数,但我无法理解它是如何工作的。您可以提供给我的任何帮助或指导都将受到赞赏。
非常感谢!
答案 0 :(得分:0)
你走在正确的道路上!使用“ScoringService”将是实现它的正确方法。
服务只是可以在各种控制器之间共享的对象。创建服务的方式是在app模块上使用“service”方法:
var app = angular.module('myApp', [])
app.service('serviceName', function(){
this.tally = function(scores){
// Do some tallying and return result
}
});
您可以通过将其注入函数来调用控制器中的服务:
app.controller('myCtrl', function(serviceName){
// now you can invoke the tally function within your controller by doing:
serviceName.tally(scores)
});