I have created a directive that will display alternative questions in an html template:
app.directive('altQuestion', ['$http', function($http) {
'use strict';
var directive = {
restrict: 'E',
transclude: true,
scope: {
json: '@',
data: '='
},
template: function() {
return '<div ng-repeat="item in questionData" name="{{item.key}}" class="{{item.class}}"> '+
'<label class="labelHeading"> '+
'{{item.labelHeading}} '+
'</label> '+
'<span ng-repeat="q in item.questions"> '+
'<label>{{q.label}}</label> '+
'<input '+
'type="{{q.type}}" '+
'name="{{item.key}}" '+
//'ng-model="{{item.data}}" '+
'value="{{q.value}}" '+
'required'+
'/> '+
'</span> '+
'</div>';
},
link: link
};
return directive;
function link(scope, elem, attr) {
$http.get('/json/alt_questions.json').
then(function(json) {
scope.questionData = json.data;
//console.log(scope.data);
angular.forEach(scope.questionData, function (v, i) {
angular.forEach(scope.data, function (k, index) {
if (v.key === index) {
console.log(v.data);
}
});
});
});
}
}]);
The data i need to bind is in
scope.data
and the question info in the json looks like this:
[{
"key": "head_brain",
"dependent": "",
"data": "visit.data.head_brain",
"class": "optionBox",
"labelHeading": "Head/brain injuries or illnesses?",
"questions": [{
"label": "No",
"value": "0",
"type": "radio",
"req": true,
"dis": false
}, {
"label": "Yes",
"value": "1",
"type": "radio",
"req": true,
"dis": false
}, {
"label": "Not Sure",
"value": "2",
"type": "radio",
"req": true,
"dis": false
}],
"comments": "",
"commentKey": ""
}, {
"key": "seizures",
"dependent": "",
"data": "visit.data.seizures",
"class": "optionBox",
"labelHeading": "Seizures or Epilepsy?",
"questions": [{
"label": "No",
"value": "0",
"type": "radio",
"req": true,
"dis": false
}, {
"label": "Yes",
"value": "1",
"type": "radio",
"req": true,
"dis": false
}, {
"label": "Not Sure",
"value": "2",
"type": "radio",
"req": true,
"dis": false
}],
"comments": "",
"commentKey": ""
}]
I need to bind the scope.data to ng-model on each question that is generated. Would I create an angular.each over the form? How could I do that in the isolated scope?
Here is a plunker: http://plnkr.co/edit/REOg53RgGUwb0OF3Fn1f
What needs to happen in the plunker is that the radio buttons need to be selected when it loads according to the data set in the main controller which is passed into the isolated scope.