这是一份问卷调查申请表。 我有一个指令,它是一系列用于在问题上做出选择的按钮。每个问题都是一个JSON对象,其中包含选择的分数。我希望突出显示与所选分数相对应的按钮,以及单击未选中按钮以更改分数。
我还没有在控制器中编写updateQuestion(),因为我需要先了解如何让他们先用Angular方式进行交谈。
按钮指令
giftsAppsModule.directive('questionChoice',function(){
return {
restrict: 'E',
replace: true,
template :'<div class="btn-group btn-group-vertical">' +
'<button class="btn btn-block" ng-click="updateQuestion(5)">Love It</button>' +
'<button class="btn btn-block" ng-click="updateQuestion(3)">Enjoy It</button>'+
'<button class="btn btn-block" ng-click="updateQuestion(2)">Maybe</button>' +
'<button class="btn btn-block" ng-click="updateQuestion(1)">Probably not</button>'+
'<button class="btn btn-block" ng-click="updateQuestion(0)">No way!</button></div>'
}
问题
questionlist= [
{"index": 1, "question": "Rejoice in God's provision even when the checkbook is in the red.", "gift": "FTH", "score": null},
{"index": 2, "question": "Clean the kitchen once a week.", "gift": "SVC", "score": null},
{"index": 3, "question": "Build sets for a drama.", "gift": "CFT", "score": null},
{"index": 4, "question": "Search the Bible to check the validity of a sermon or Bible lesson.", "gift": "DSC", "score": null}]}
相关的html
<div ng-repeat="question in questionlist">
<div class="row-fluid">
<div class="span6">
<p>{{question.index}}. {{question.question}}</p>
</div>
<div class="span6">
<question-choice></question-choice>
</div>
</div>
</div>
答案 0 :(得分:1)
我认为您需要将问题与响应相关联,因此您可以让指令创建一个隔离的范围以便传递模型。(如果不创建隔离范围,您可以访问指令内的模型,但是该指令将失去其可重用性。因此最好使其成为独立的。)
App.directive('questionChoice', function () {
return {
restrict: 'E',
replace: true,
scope: {
ngModel: '='
},
template: '<div class="btn-group btn-group-vertical">' +
'<button ng-class="{\'button-hl\':ngModel.score == 5}" class="btn btn-block" ng-click="updateQuestion(ngModel, 5)">Love It</button>' +
'<button ng-class="{\'button-hl\':ngModel.score == 3}" class="btn btn-block" ng-click="updateQuestion(ngModel, 3)">Enjoy It</button>' +
'<button ng-class="{\'button-hl\':ngModel.score == 2}" class="btn btn-block" ng-click="updateQuestion(ngModel, 2)">Maybe</button>' +
'<button ng-class="{\'button-hl\':ngModel.score == 1}" class="btn btn-block" ng-click="updateQuestion(ngModel, 1)">Probably not</button>' +
'<button ng-class="{\'button-hl\':ngModel.score == 0}" class="btn btn-block" ng-click="updateQuestion(ngModel, 0)">No way!</button></div>',
link: function (scope, element, attrs) {
scope.updateQuestion = function (question, v) {
question.score = v;
}
}
}
});
对于按钮突出显示,您可以使用ng-class
逻辑来实现。请看一下演示。
的 Working Demo 强>