Looking for a solution to dynamically render forms with various controls based on a specific Type value specified in a JSON object. The form will be created based on user input, so the necessary question types may vary. While we will define the types, they can appear in any sequence as inputted by the user.
{
"Name": "Getting to know you.",
"Id": "870tVcee8irPLdhi14fSZw==",
"Controls": [
{
"Type": "Text",
"Label": "First Name",
"Id": "vF4z8YcSlpJGsF9fDw5TpA==",
"Color": "FFFFFF",
"Required": "True",
"Validaion": "False",
"ValidationRegEx": "",
"ErrorText": ""
},
{
"Type": "Picklist",
"Label": "Last Name",
"Id": "vF4z8YcSlpJGsF9fDw5TpA==",
"Color": "#CCCCCC",
"Required": "True",
"Validaion": "False",
"ValidationRegEx": "",
"ErrorText": "",
"PicklistVals": ["1","3","5"]
}
]
}
The directive must identify the control type and then pass it to determine which template to render.
<div ng-repeat="control in section.Controls">
<input-parser ele="{{control}}"></input-parser>
</div>
app.directive('inputParser', function() {
function getTemplate (control) {
var template = '';
switch(control.Type) {
case 'Text':
template = '<form style="color:' + control.Color + '">template2</form>';
break;
case 'Picklist':
template = '<form style="color:' + control.Color + '">template2</form>';
break;
}
return template;
}
return {
restrict: "E",
scope: {
control: '@'
},
template: function() {
return getTemplate(control));
}
}
Two questions:
Is there a way to access scope variables in the template attribute of a directive that are loaded dynamically? I am only able to hard code them currently due to the bindings not being set before parsing the directive.
Is this an effective method for rendering dynamic templates that require access to information passed into the directive? Should I simply access the root scope instead of using scope variables?