Developing a custom directive that dynamically alters the DOM by appending child directives based on the current scope

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?

Answer №1

For those in search of data-driven forms, consider checking out formly:

The developer behind this project discusses a similar issue in this informative video: https://www.youtube.com/watch?v=o90TMDL3OYc

Answer №2

Big thanks to @charlietfl for catching my error. I've now rectified the final section of my code as shown below:

if (questionHtml) {
  var link = $compile(questionHtml);
  var compiled = link(scope);
  element.append(compiled);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular: Revise information in a table row

Hi there, I am currently in the process of learning Angular and could use some assistance with a specific functionality. I have a dynamic table and a form set up, and my goal is to populate the input boxes in the form with data from any row of the dynamic ...

Tips for troubleshooting the issue of "Jest detecting a lingering open handle that could prevent Jest from exiting"

Currently, I am facing new challenges with async code in Jest. Previously, my question (related to async code in a Jest bootstrap) caused issues. Now, my focus is on executing async database calls within the tests. The objective is to establish connections ...

Tips for halting a MySQL database transaction within a NodeJS environment using expressJS

Recently, I encountered a coding challenge that involved managing a long database transaction initiated by a user. The scenario was such that the user inadvertently updated 20 million entries instead of the intended 2 million, causing a significant impact ...

Schema with nested object types in MongoDB

I currently have two schema files in my project. In the events.js file, I have an eventSchema defined. Here is a snippet of the code: var eventSchema = mongoose.Schema({ name:{ type: String, //required: true venue:{ } }); In another file named ve ...

Can someone explain the crazy math used in three.js?

I've recently started learning three.js, and I keep encountering these complex mathematical formulas that seem confusing. Take this example for instance: mouse.set( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeig ...

What is the best way to send information to a different webpage?

I am in search of a solution to a rather simple query that has me puzzled. Should this question already exist elsewhere, I humbly request that you guide me to the answer. My apologies in advance if this is a duplicate. I currently have two URLs: http://12 ...

Utilize Typescript to aim for the most recent edition of EcmaScript

Are you looking to configure your typescript build to compile to the most recent version or the most current stable release of EcmaScript? For example, using this command: tsc --target <get latest version> Alternatively, in a tsconfig file: { & ...

Having trouble importing JS into HTML file with NodeJS

I have created a web server using NodeJS that serves the file index.html. However, when I attempt to add a JavaScript file to my HTML document, the browser displays an error message stating The resource "http://localhost:3000/includes/main.js" was blocked ...

Check the Full Calendar to see if any events are scheduled for today

I have a group of users who need to save their availability. Currently, I am utilizing Full Calendar and looking for a way to prevent them from adding the same event multiple times on a single day. My tech stack includes VueJs and all events are stored in ...

Connecting JSON objects based on unique GUID values generated

I am in search of a method to automate the laborious task of linking multiple JSON objects with random GUIDs. The JSON files are all interconnected: { "name": "some.interesting.name", "description": "helpful desc ...

"After the document is fully loaded, the Ajax post function is failing to work

I am looking to trigger an Ajax call once my document has finished loading. Here is the code I currently have: <script> $(window).bind("load", function () { getCategories(); }); </script> <script> ...

Error encountered when using the Jquery append function: Anticipated ')' issue

While working on my PHP file, I encountered an issue with an AJAX request. The request is returning the correct value, however, when attempting to use the append function in jQuery, it results in an error being displayed in the console. $.ajax({ ...

Tips on organizing JSON data with JavaScript

After receiving my $http response, the data is presented in the format below: $scope.rooms = { '2B' : [ {"RoomEmailId":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ebd9a9c6d8d9d8ab868ec5888486" ...

What is the best way to set the state to false upon unmounting a component in react?

Currently, I am controlling the state of a dialog using context. Initially, the isOpen state is set to false. When the add button is clicked, the state isOpen becomes true and clicking the cancel button will revert it back to false. If the user does not c ...

The ng-model does not reflect changes when using the JQuery datepicker

Currently, I have set up two textboxes for users to choose a date. I am utilizing JqQuery's datepicker UI to showcase a small calendar pop-up whenever the user clicks on the textbox. However, an issue arises when I select a date in the calendar popup ...

What advantages does using 'async' offer for TypeScript functions that already have a Promise return type?

Is there any advantage to declaring a TypeScript function as async if the return type is already a promise? It seems like both methods achieve the same result: function foo(): Promise<Bar> { } //vs async function foo(): Bar { } //Or even async fu ...

Angular controller: Utilize the $filter service to sort by integers

My information is currently arranged as strings: ID Name 1122162089 John McGill 1461 Cynthia Salazar 22925 Sylvan Knutsen 24930 Amrit Advani I am looking to organize it as numerical values var sortedData = function (records, ...

Showing fixed values inside directive view after successful injection

Looking for some answers about using constants in angularjs. Here are the constants defined in my app.js: ... angular .module('blocTime', ['firebase', 'ui.router']) .config(config) .constant(&apos ...

Utilize DOM to attach a button onto an image

I am looking to add buttons onto images using DOM manipulation. Each image will have multiple buttons that, when clicked, will delete the image. I am aiming for a functionality similar to this example - JSFiddle This is the code I have attempted so far: ...

JavaScript Sort function malfunctioning and not correctly sorting

I am having trouble sorting div elements by price values. The code seems to be working fine, but the sorting of numbers doesn't appear to be completely accurate. For example, in my jsfiddle, when the button is clicked, the number 21.35 is displayed a ...