0

使用 AngularJS 我正在尝试创建一个指令来模板化表单中的问题。对于特定类型的问题,我想为特定范围内的每个数字创建单选按钮。我有一个外部函数,它返回一个给定下限和上限的数字数组。

如何使用这个外部函数和 ng-repeat 来模板化这类问题?这是我到目前为止尝试过的代码......

HTML:

<qtnrange qtn-variable="cxnTestVarA" first-num="1" last-num="5">
This is a test question. Pick a number between 1 and 5.</qtnrange>
<hr>
You picked {{cxnTestVarA}}.

JS:

var module = angular.module('app', [])
.directive('qtnrange', function() {
return {
    scope: {
        qtnVariable: '=',
        firstNum: '=',
        lastNum: '=',
        bounds: '&range',
    },
    template:
        '<div class=question>' + 
            '<label ng-transclude></label>' +
            '<label class="radio inline" ng-repeat="iter in bounds(firstNum, lastNum)"><input type="radio" value="{{iter}}" ng-model="qtnVariable">{{iter}} </label>' +
        '<hr></div>',
    restrict: 'E', // must be an HTML element
    transclude: true,
    replace: true,
};
});

var range = function(start, end, step) {
    ... function that returns an array []
}
4

1 回答 1

2

这是您的 jsFiddle 的一个工作示例:http: //jsfiddle.net/daEmw/3/

我所做的是将范围函数移动到示波器上,并在无线电输入上使用 ng-click,而不是将它们与 ng-model 绑定。

基本上,改变这个:

module.directive('qtnrange', function() {
    return {
        scope: {
            qtnVariable: '=',
            firstNum: '=',
            lastNum: '=',
            bounds: '&range',
        },
        template:
            '<div class=question>' + 
                '<label ng-transclude></label>' +
                '<label class="radio inline" ng-repeat="iter in bounds(firstNum, lastNum)"><input type="radio" value="{{iter}}" ng-model="qtnVariable">{{iter}} </label>' +
            '<hr></div>',
        restrict: 'E', // must be an HTML element
        transclude: true,
        replace: true,
    };
});

var range = function() {

}

进入这个:

module.directive('qtnrange', function() {
    return {
        scope: {
            qtnVariable: '=',
            firstNum: '=',
            lastNum: '='
        },
        template:
            '<div class=question>' + 
                '<label ng-transclude></label>' +
                '<label class="radio inline" ng-repeat="iter in range(firstNum, lastNum)"><input type="radio" value="{{iter}}" ng-click="setNum(item)">{{iter}} </label>' +
            '<hr></div>',
        restrict: 'E', // must be an HTML element
        transclude: true,
        replace: true,
        controller: function($scope) {
            $scope.setNum = function(num) {
                $scope.qtnVariable = num;
            }
            $scope.range = function() {
                // ...
            }
        }
    };
});
于 2013-02-20T16:01:38.870 回答