Creating a dynamic template in AngularJS directive

I am curious about how to create a dynamic template directive. Here's the challenge - when I am on the main page or main categories such as page1 or page2, my template should include all the divs.

However, when I am on a submenu like subpage1 or subpage2, I only want to display 3 divs. How can I dynamically accomplish this? I understand that I need to use my directive on each subpage.

For example:

<my-template whereIam="page1"></my-template>
or
<my-template whereIam="subpage2"></my-template>

Unfortunately, I am struggling to implement this. Can anyone provide guidance?

Here is my directive with an example template:

angular.module('dynamic-template').directive('myTemplate', function () {
    return {
        restrict: 'E',
        template: "<div1> "
                    + "<h1> Main pages and subpages </h1>"
                + "</div1>"
                + "<div2>"
                    + "<h2> Main pages and subpages </h2>"
                + "</div2>"
                + "<div3>"
                    + "<h3> Main pages and subpages </h3>"
                + "</div3>"
                + "<div4>"
                    + "<h4> Only mainpages </h4>"
                + "</div4>"
                + "<div5>"
                    + "<h5> Only subpages </h5>"
                + "</div5>"                     
    };
}]);

Here is the HTML on one of the pages:

<my-template whereIam="??" ></menu-template>

Check out this Plunkr for an example:

http://plnkr.co/edit/kVk3mJWUbTqhFEHVUjt1?p=preview

I have tried looking for a solution but I'm feeling overwhelmed. Should I use $compile to make this work?

Answer №1

*note: My personal preference is to keep the template in a separate file using templateUrl.

However...

If you pass through the page-type of page and use ng-if's.

angular.module('dynamic-template').directive('myTemplate', function () {
return {
    restrict: 'E',
    scope: { isMain: "=main"},
    template: "<div1> "
                + "<h1> Main pages and subpages </h1>"
            + "</div1>"
            + "<div2>"
                + "<h2> Main pages and subpages </h2>"
            + "</div2>"
            + "<div3>"
                + "<h3> Main pages and subpages </h3>"
            + "</div3>"
            + "<span ng-if='isMainPage'><div4>"
                + "<h4> Only mainpages </h4>"
            + "</div4>"
            + "<div5>"
                + "<h5> Only mainpages </h5>"
            + "</div5></span>"                     
};
}]);

and in your html (when it is a main page)

<my-template main="true"/>

Alternatively, my response to a similar question may also be helpful:

This method does involve creating separate html files for each file.

Check out another Stackoverflow answer

or you can view it directly on Plunkr

Plunkr

app.directive('myDirective', [function(){

return {
    template: '<div ng-include="getTemplate()"></div>',
    restrict: 'E',
scope: {template: '='},
link: function(scope, element, attr, ctrl) {
  var baseURL = 'templates/myDirective.'

  scope.getTemplate = function(){
      baseURL = "" //remove this
      return baseURL + scope.template + ".html"
    };
}
};
}]);

Answer №2

Instead of using inline template code, consider following rmuller's suggestion and utilize a templateURL method. This way, you can pass parameters and return the appropriate template based on the conditions.

templateUrl: function (element, attributes) {
                if (attributes.isMain === 'mainPage') {
                    return 'main_view.html';
                }
                return 'other_view.html';
            },

By organizing your templates into separate files, you can enhance code readability and maintainability. This approach receives my preference in terms of best practices.

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

Determine the date 7 days before today using JavaScript

I've been trying to calculate the date that is 12 days before today's date, but I'm running into an issue where it's not returning the correct result. For instance, if today is November 11, 2013 (mm/dd/yyyy), the code returns October 30 ...

Utilize the power of React and Framer Motion to create a visually stunning fade

After creating a preloader that appears when the variable "loading" is set to true, I now want the loader to fade out. This is an overview of my files: On the home page with all the content: return ( <> {loading ? ( ...

Position the column content to the right side of the cell using React MUIDataTable

I'm a beginner with MUI and I need assistance aligning the content of a column to the right. Here is my code snippet: <MUIDataTable title={""} data={data || []} columns={realColumns ? realColumns(data, modeMO) : columns(data, modeMO ...

"Regarding compatibility with different browsers - IE8, Firefox3.6, and Chrome: An inquiry on

Snippet of JavaScript Code: var httprequest = new XMLHttpRequest(); var time = new Date(); if (httprequest) { httprequest.onreadystatechange = function () { if (httprequest.readyState == 4) { alert("OK"); } }; httprequest.open("GET", ...

Coloring a table in vue.js based on performance rankings

I'm facing an issue with sorting my data performance in vue js. Here is the script I have created so far: <template> <div> <div class="row"> <h2> Campaign Performance </h2> <table class=&q ...

Animation does not occur after the stop() function is executed

My goal is to create a functionality where, upon moving back to the grey content box after leaving the button, the slideUp animation stops and the content slides down again. This works seamlessly with jQuery 1.x (edge), but when I switch to jQuery 1.10, th ...

utilizing dropzone.js to pass an index and invoke a function

While everything seems to be functioning correctly, there is a notable issue that I am facing. When I upload an image to my Dropzone instance, I want the file name of that image to be added to the cards array under imageInfo. The challenge lies in figurin ...

Guide to periodically updating and displaying a <b-img> element in VueJS

Recently delving into the world of JS and Vue. Within my Bootstrap-Vue project, there's an image element that looks like this: <b-img src="/api/camera" fluid alt="camera"></b-img> Whenever the page is refreshed, the br ...

Using JavaScript functions to modify the style of the DOM

Is there a way to change the style of a dom element using JavaScript when only the element id and style value are passed as parameters, without passing the actual style parameter itself? For example, is it possible to use the id "first" and set the color ...

Galaxy S5 browsers experiencing issues with website responsiveness

I've been using jquery to dynamically remove a div in order to change the appearance of my home screen on smaller devices. It's been successful on my Macbook Air and Iphone X, but unfortunately, it doesn't seem to work properly on Android de ...

Storing JWT API tokens in a secure location

Currently, I am in the process of developing the API portion for an application and focusing on implementing JWT authentication. At this point, I am generating a token and sending it back to the front-end as part of a JSON object when a user is created. Ho ...

Guide on showcasing an array of objects in HTML with the help of the template element

My goal was to populate the HTML page with an array of objects using the template element. However, I made a mistake and only the last object in the array was displayed correctly on the page. Can anyone help me identify my error and suggest a correction? I ...

What is the method to determine the index of a removed element within a subarray?

In my array, all = [2,3,4,12, 55,33], there is a sub-array named ar1 = [12, 55, 33] starting from the value 12. If I remove a value from all that is present in ar1 (e.g. 12), how can I determine the index of this value in ar1 (0 for 12) so I can also remo ...

Solving issues with Angular4 Router changes

I'm attempting to chain the router resolver for my application. Below are my Router options: { path: '', component: AdminComponent, resolve: [ SessionResolve, LocaleResolve ] } The desired flow is to first call S ...

ExpressJS looping back

After exploring and practicing the creation of Rest APIs with both Loopback and ExpressJS individually, When using Loopback: I found it to be quite time-consuming to go through all the documentation and learn about loopback-specific features. However, i ...

What causes the selected option to be hidden in React?

I created a basic form demo using react material, featuring only one select field. I followed this link to set up the select options: https://material-ui.com/demos/selects/ With the help of the API, I managed to display the label at the top (by using shri ...

Leveraging the useRef hook to adjust the CSS styling of a React component

Currently, I am working on changing the style of a react component by utilizing the useRef hook. So far, I have implemented the useRef hook to reference the specific component whose style I want to modify when clicking on two buttons. Despite my efforts, I ...

Navigate to a fresh HTML page upon form submission

I'm completely new to the world of web apps and JavaScript, and I'm facing an issue where my form submission doesn't redirect me to a thank you page. Instead, it just leads to a blank page every time. I've tried researching solutions on ...

Allow the javascript callback function to complete before proceeding

Utilizing the Google Storage API, I am saving a file in a GCP bucket within an asynchronous function. My objective is to wait until I receive an error or success callback before proceeding with the subsequent lines of code. However, I am encountering the i ...

Issue - Following error occurred in the file connection.js located in node_modules/mysql2 library: Module not found: Unable to locate 'tls' module

I've encountered an error in our Next JS applications where tls is not found. I have tried several troubleshooting steps including: 1. Updating Node modules 2. Using both mysql and mysql2 3. Running npm cache clean --force 4. Removing node_modules di ...