I'm currently working on developing a dynamic questionnaire system in Angular that can handle various question types and display them differently based on their characteristics. Instead of using multiple ngIf directives for each question type, I decided to encapsulate the logic within a directive for a more streamlined approach. Here's what I came up with:
angular.module('membercenter.riskquestionnaire')
.directive('pnDynamicQuestion', function ($compile) {
return {
restrict: 'E',
scope: {
question: "=model"
},
link: function(scope, element, attrs) {
var question = scope.question;
var questionHtml = null;
if (question.type === 'SingleAnswerQuestion') {
questionHtml = '<pn-single-answer-question model="question"></pn-single-answer-question>';
} else if (question.type === 'MultipleAnswerQuestion') {
questionHtml = '<pn-multiple-answer-question model="question"></pn-multiple-answer-question>';
} else if (question.type === 'NumericSingleAnswerQuestion') {
questionHtml = '<pn-single-answer-incremental-question model="question"></pn-single-answer-incremental-question>';
}
if (questionHtml) {
var questionElement = angular.element(questionHtml);
var compiled = $compile(questionHtml);
element.append(questionElement);
compiled(scope); // Compile the specific question type directive
}
}
};
});
Although this approach correctly adds the HTML elements for different question types, I encountered an issue where the specific question type directives are not being rendered on the browser. Can anyone offer some guidance on how to resolve this?