Using AngularJS I'm attempting to create a directive to templatize questions in a form. For a particular type of question, I want to create radio buttons for each number within a certain range. I have an external function that returns an array of numbers given a lower and upper bound.
How can I use this external function, together with ng-repeat, to templatize this type of question? Here's the code I've tried so far...
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 []
}
Here's a working example of your jsFiddle: http://jsfiddle.net/daEmw/3/
What I did was moving the range function onto the scope, and to use ng-click on the radio inputs instead of binding them with ng-model.
Basically, changing this:
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() {
}
into this:
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() {
// ...
}
}
};
});