1

这是一个问卷应用程序。我有一个指令,它是一系列用于对问题做出选择的按钮。每个问题都是一个带有选择分数的 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>
4

1 回答 1

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

于 2013-09-03T01:46:58.110 回答