Utilizing directive scope variables to generate dynamic templates

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:

  1. 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.

  2. 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?

Answer №1

If the directive input-parser only displays the form without any additional functionalities, you might want to consider using ng-include instead. This way, you can store all your templates as partials.

Check out the demo here

<ng-include ng-repeat="control in section.Controls" src="control.type + '.html'"></ng-include>

On the other hand, if the input-parser directive needs to share some behavior across all templates, you can use the above ng-include as a template instead.

Javascript

  .directive('inputParser', function() {
    return {
      restrict: 'E',
      scope: {
        control: '='
      },
      template: '<ng-include src="\'form\' + control.type + \'.html\'"></ng-include>'

      // controller: function() {}, // attach your controller behaviour
      // link: function() {} // attach your element behaviour
    };
  });

HTML

<input-parser ng-repeat="control in section.Controls" control="control"></input-parser>

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

Function activation in Element requires a double click to initiate

I've encountered an issue with a web element I'm working on where the click function only triggers after the first click, rendering the initial click ineffective. Here's the code snippet in question: HTML: <div> <a href="#0" cla ...

A problem arises when the React effect hook fails to trigger while utilizing React Context

I have created a component that is supposed to generate different pages (one for each child) and display only the selected page: import * as React from "react"; export interface SwitchProps { pageId: number; children: React.ReactChild[]; } ...

"Utilizing the power of Node.js to perform SQL queries with

I'm having trouble with this SQL query that uses INNER JOIN. The query is returning an error. connection.query("SELECT caracavis.caracname FROM caracavis WHERE firstcaturl ='" + req.body[0].firstcatname + "' AND secondcaturl = '" + r ...

Navigating state: (TypeError): The mapping function for this.state.[something] is invalid

I am currently working on iterating through my state, which contains data retrieved from an external API. However, I encountered this error message: TypeError: this.state.stocks.map is not a function My goal is to display the results on the frontend dyn ...

The click event does not seem to be functioning properly within a contenteditable div

Incorporating a delete button within the div would allow users to delete it upon clicking. However, there are currently two issues: (1) The alignment of the delete button with the text in the div is not accurate. (2) The click event for the button is not ...

Issue: encountered an ECONNRESET error when attempting to read using the request module in mode.js

When attempting to download and parse large XML files from affiliate sites without a proper API, I encounter the same error consistently while using the request module for Node.js. Error: read ECONNRESET at exports._errnoException (util.js:746:11) at TCP. ...

Is Riot.js the best choice for server-side rendering and routing?

Currently, I am using Node along with Riot.js and the Grapnel routing library. I have successfully set up routing on the client side, but I am facing difficulty in making it work on the server side. The functioning of my client router is straightforward. ...

When incorporating <Suspense> in Next.js, the button's interaction was unexpectedly lost

'use client' import React, { Suspense } from "react"; const AsyncComponent = async () => { const data = await new Promise((r) => { setTimeout(() => { r('Detail'); }, 3000) }) as string; return <div>{d ...

Node.js: The Ultimate Solution for Automatic Data Saving

Currently, I am working on a collaborative project using Node.js, MySQL, and React. I have encountered some difficulties with the ToDo list section. I would appreciate any advice on the best and quickest method to automatically save data or options to the ...

What is the best way to incorporate an image that appears when a user clicks on a

My goal is to dynamically place an image exactly where a user clicks on the webpage. Currently, I have the following code, but it only adds the image at the top and continues to do so repeatedly...not appearing at the clicked location. <html> ...

Encountered a snag with submitting data via AJAX: received an error message stating

I created this custom script for a contact form on my website, and it seems to be working fine. However, I'm encountering an issue where instead of storing the data in my database, all I get is [object HTMLCollection]. Can someone please explain wh ...

Upon page refresh, products are automatically added to the cart

While developing a shopping cart code, I encountered an issue where refreshing the page automatically added a product to my cart without any action from me. For instance, my website displays three products: Apple, Banana, Orange. When I click on Apple, it ...

What are the steps to crafting a basic JavaScript or jQuery function within CodeIgniter?

I'm currently working on creating a basic JavaScript function within CodeIgniter that is triggered when a radio button is clicked. <input type="radio" name="amount" value="<?php echo $plan['amount']; ?>" onclick="fn()" /> The J ...

What could be causing my JavaScript code to not function properly in an HTML document?

Hello, I am a beginner in the world of coding and currently delving into web development. Recently, I was following a tutorial on creating a hamburger menu but I seem to be encountering some issues with the JavaScript code. I have double-checked my Visual ...

Combining two JSON objects in JavaScript is simple when their IDs correspond to each other in both objects

I have a query related to merging two different objects from the database, both in JSON format. These two objects share two key/value pairs: IRBId = ... and id = ..., which can be seen in the examples below: OBJ 1 { "data":{ "IRBs":{ "n ...

ng-repeat fails to initiate $destroy on a particular element

After creating a custom directive to use within ng-repeat, I encountered an issue with the remove button. Whenever I click on the remove button to delete a specific element from the list, the $destroy event is triggered on the last element in the list inst ...

display a dialogue box when clicked, containing radio buttons

I am currently developing a practice exam for students at my school. The exam consists of multiple choice questions, and I have hit a roadblock in the coding process. Being new to javascript, I am struggling to figure out how to make it function properly. ...

React search form submits separate search each time a new input is is added to the form

A unique approach is being used to dynamically create the search form by making an ajax call for the inputs. Each input can be used alone or in combination with others to refine the search results. The issue arises when the submit method triggers a new sea ...

Can you tell me the alternatives for getServerSideProps and getStaticProps in Next.js version 14?

I'm trying to wrap my head around the rendering behavior of SSR/SSG/ISR in Next.js version 14 with the updated app router. Previously, Next.js provided predefined functions like getServerSideProps for server-side fetching and processing (SSR), or getS ...

Unable to verify $http using passport Basic Authentication

How do I implement $http call with basic auth using Passport? I have successfully set up basic authentication with Passport on my server and can test it using POSTMAN. However, when trying to implement it in my Angular application, I am facing issues pass ...