Tips for incorporating dynamic parameters/variables into templates displayed using ng-bind-html or a custom directive (within ng-repeat)

EDIT: I have created a solution sample based on the initial answer. However, I am open to further suggestions and would appreciate any help in filling the gaps in my knowledge (please refer to the comments). plnkr.co/edit/mqGCaBHptlbafR0Ue17j?p=preview

ORIGINAL POST

Greetings to all Angular enthusiasts,

I am currently working on developing a tool for constructing simple web pages using a predefined set of elements. The user will be able to design the layout by selecting which elements appear in what order (around 20-30 different elements to choose from). Here's an example layout:

Heading
Paragraph
Paragraph
Subheading
Barchart
Paragraph

...and so forth

Behind the scenes, there will be an array of JavaScript objects:

var page_structure = [
{type: "heading", content: "The final exam - details" },
{type: "paragraph", content: "Lorem ipsum dolor sit amet..." },
{type: "paragraph", content: "Lorem ipsum dolor sit amet..." }
...
{type: "bar chart", y: "Grades", colour: "blue" }
...
];

The user will input parameters such as content, variable, color, etc., for each individual element.

THE ISSUE

I am struggling to figure out how to render these elements on the page while ensuring that the dynamic parameters for each element are correctly included.

Each element type (heading, paragraph, bar chart, or any other possible element) has its own HTML template, which must be able to dynamically display user-defined parameters. I believe I need something along these lines:

var templates = {
heading: "<h1>USER_CHOSEN_PARAMETER_HERE</h1>",
paragraph: "<p>USER_CHOSEN_PARAMETER_HERE</p>"
...
};

I am utilizing Angular's ng-repeat directive to render each element. I have tried implementing ng-html-bind...

<div ng-repeat="x in page_structure track by $index">
   <div ng-bind-html="templates[x.type]"></div>
</div>

...or a custom directive called 'mycomponent':

<div ng-repeat="x in page_structure track by $index">
   <div mycomponent component='x'></div>
</div>

Both methods work smoothly when there are no user-defined parameters in the templates. However, I am unable to incorporate the parameters. With ng-bind-html, I attempted using expression markup like this:

var templates = {
heading: "<h1>{{x.content}}</h1>",
paragraph: "<p>{{x.content}}</p>",
...
};

(I typically define the templates in the app controller constructor, so it's $scope.templates = { blah blah } to be more specific.)

Instead of rendering the dynamic variables as intended, the actual webpage displays curly braces and "x.content". How can I reference a dynamically variable parameter within an ng-html-bind template, or is it even feasible?

I also explored the custom directive route, defining the directive as:

.directive('mycomponent', function() {
        return {
                scope: { component: "=" },
                template: templates[component.type]
    }; )

This approach led to confusion as I struggled to identify how to reference a dynamic parameter inside the template. Apologies for not being able to provide a clear example of what I attempted to achieve.

Any assistance or functional examples of the techniques I should employ here would be highly appreciated. Feel free to request additional information if necessary (as this is my first post on SO, I am still learning how to structure questions effectively).

Answer №1

If you're looking for a way to dynamically load templates in AngularJS, I recommend using the ngInclude directive. You can create a function that determines which template to load based on the structure of the page.

<div ng-repeat="structure in page_structure">
    <div ng-include="getMyTemplate(structure)"></div>    
</div>

$scope.getMyTemplate = function(structure) {
    switch (structure.type) {
        case 'heading':
            return '/Views/Heading.html' // or id of a pre-loaded template
        case 'paragraph':
            return '/Views/Paragraph.html' // or id of a pre-loaded template
    }
}

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

AJAX response for form validation

I need to validate my contact form when the submit button is clicked. If all fields are valid, I want to display a Processing message using AJAX, followed by a success message with the entered name. The content of my Form is: <form onsubmit="return va ...

change the return value to NaN instead of a number

Hey there, I have something similar to this: var abc1 = 1846; var abc2 = 1649; var abc3 = 174; var abc4 = 27; if(message.toLowerCase() == ('!xyz')) { client.say(channel, `abc1` +`(${+ abc1.toLocaleString()})` +` | abc2 `+`(${+ abc2.toLocaleStri ...

Guide on darkening the surrounding div of an alert to give it a modal-like effect

I want to display an alert to the user in a visually appealing way. To achieve this, I am utilizing Bootstrap's alert class. Here is how I am showing the user a div: <div class="alert alert-warning alert-dismissible" role="alert"> Some text ...

Setting an action when clicking on a slice of a Doughnut chart using Chart.js

I have been working on integrating chart.js into my Django Project, and so far it has been going smoothly. I successfully created a doughnut chart with two slices. Now, I am trying to implement separate actions for each slice when clicked, such as redirect ...

Formik Fields with unique key properties

When mapping text fields, I follow this structure: { AddVehicleFields.map(({formikRef, ...input}) => ( <> <TextField key={formikRef} helperText={ getIn(formik.touched, formikRef) ? getIn(formik. ...

Ways to ensure Vue retrieves data from the database whenever a specific event occurs

I have individual buttons next to each row, with unique data entries in the database. When clicking on a button, I want specific information to appear in a Bootstrap Modal. However, I am facing challenges ensuring that Vue updates correctly with each click ...

Questions on how to utilize ES6 Express and static methods

Recently, I've been working with Express and wanted to incorporate ES6 using babel in my project. One question that has been on my mind is related to the use of static methods for handling requests, as shown below: class MyCtrl { static index (r ...

Is there a way to mount or unmount a React component by pressing a single key?

I am currently developing an application that showcases 3D objects upon pressing certain keys on the keyboard. My goal is to have these objects disappear after 2-3 seconds or once the animation completes. Below is the component responsible for managing th ...

What could be the reason for my ajax request coming back with no data?

When I make this ajax request: $.ajax({ type: "POST", url: "/admin/RoutingIndicators/Add", data: { newSecondaryRI: newRi }, success: function () { alert('hit'); document.location.reload(true); }, error: fu ...

Is there a Javascript tool available for creating a visual representation of the correlation between items in two separate

Does anyone have recommendations for an HTML/JavaScript/browser-based component that can map items in one list to another? Imagine a scenario where there is a list of items on the left-hand side and another list on the right, with the ability to click on a ...

Tips for organizing a CodeIgniter application using AngularJS

I'm looking to develop an application that utilizes CodeIgniter for the backend and AngularJS for the frontend. Currently, I understand that we can use Angular JS $http service to retrieve data from Codeigniter. However, I'm unsure about how to ...

Looking to change the date format from 24/05/2021 to 24/May/2021 using jQuery or JavaScript?

My client prefers not to use a date picker, but wants to be able to type dates directly into a textbox and have them automatically converted to the format 24/May/2021 as they leave the field. I am looking for a solution using either Javascript or jQuery. ...

What is the best way to extract information from my MYSQL database and represent it as an array?

Currently, I am working on a backend API that utilizes a MySQL database. My goal is to extract data from this database and utilize it to plot latitude and longitude points on a map using the Google Maps API. To achieve this, I have integrated the Gmaps API ...

Customize the styling of an individual 'LI' item within an array by utilizing Jquery

Just starting out with Javascript and jQuery. Created a basic image slider that's running into a jQuery problem. Here's the HTML for the image list: <div id = "slider-auto"> <ul class= "slides"> <li class = "slide"&g ...

Looking for assistance with implementing a jQuery function for an onClick event on

I've been diving into learning jquery and managed to create a basic checkbox feature with a function that allows you to set all options as read-only by checking the "None of the above" button. <html> <body> <form id="diagnos ...

Establish a new <section> to serve as a distinct webpage

I have a question about creating multiple <section> elements on a page. I am looking to build an HTML document with several <section> tags, as outlined below. <html> <head> </head> <body> <sectio ...

Styled Components do not have the ability to define :hover states

export const WatchVideoButtonWrapper = styled.div` position: absolute; bottom: 80px; right: 33px; background-color: ${(props) => props.bgColor}; color: ${(props) => props.color}; border-radius: 100px; transition: all 0.1s; ...

What is the process of performing numerical calculations using jQuery?

I need to deduct certain input values from the total price. Here's the code snippet: $('.calculate-resterend').click(function(e) { e.preventDefault(); var contant = $('.checkout-contant').val(); var pin = $('.che ...

What is the process for attaching a dynamically generated object to the document's readiness event?

One of my tasks involves dynamically generating a slider element using the code snippet below: function NewDiv(){ for (var count=0; count < parseFloat(sessvars.storey_count); count++) { var string="<br><div ...

What could be causing the failure of this web component using shadow DOM when the HTML code includes multiple instances of the component?

Recently, a question was raised on this platform regarding the use of Selenium to access the shadow DOM. Curious about this topic, I delved into the MDN article Using shadow DOM and decided to replicate the code on my local machine. Surprisingly, it worked ...