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-modelでバインドする代わりに、ng-clickを使用することでした。

基本的に、これを変更します。

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 に答える