Is there a method for dynamically loading angular directives?

Check out this quick demo:

http://jsfiddle.net/aSg9D/

Essentially, both

<div data-foo-{{letterA}}></div>
and
<div data-ng:model="foo-{{letterB}}"></div>
are not being interpolated.

I'm trying to figure out a way to dynamically load one of multiple inline templates.

Apologies if this question has already been asked, but my search didn't yield any results.


I think Radim Köhler has provided the correct solution. Before their answer, I managed to put together a method to load directives from another directive using the following code:

angular.module('myApp', []).directive('loadTmpl', function($compile) {
    return {
        restrict: 'A',
        replace: true,
        link: function($scope, $element, $attr) {
            $element.html("<div data-card-"+$attr.loadTmpl+"></div>");
            $compile($element.contents())($scope);
        }
    };
});

And:

<div data-load-tmpl="{{directiveName}}"></div>

I believe this is the most minimalistic approach, but there may be some issues with it, so please refer to the answer below for more details.

Answer №1

Here is a revised version of the code using the updated fiddle. The view now looks like this:

<div my-selector name="letterA"></div>
<div my-selector name="letterB"></div>

This is how the controller has been adjusted:

function myCtrl($scope) {
    $scope.letterA = 'bar';
    $scope.letterB = 'baz';
}

Additionally, a new directive called mySelector has been created to contain the selector:

.directive('mySelector', 
  [       '$templateCache','$compile', 
  function($templateCache , $compile) {
    return {
      scope: {
        name: '='
      },
      replace: true,   
      template: '',            
      link: function (scope, elm, attrs) {

        scope.buildView = function (name) {
            var tmpl = $templateCache.get("dir-foo-" + name);
            var view = $compile(tmpl)(scope);
            elm.append(view);
        }
      },
      controller: ['$scope', function (scope) {
        scope.$watch('name', function (name) {
            scope.buildView(name);
        });
      }],          
    };
}])
.run(['$templateCache', function ($templateCache) {
    $templateCache.put("dir-foo-bar", '<div data-foo-bar></div>');
    $templateCache.put("dir-foo-baz", '<div data-foo-baz></div>');
}])

If you find this version suitable, credit goes to Render a directive inside another directive (within repeater template) and AngularJS - Directive template dynamic. If not, feel free to hold me accountable.

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

How can you make the table rows in jQuery scroll automatically while keeping the table header fixed in

Many solutions exist for making the header fixed and the table scrollable using code samples or plugins. However, my specific goal is to have the table data rows scroll automatically once they are loaded while keeping the header fixed in place. Is there a ...

Updating the @mui/x-data-grid table dynamically upon fetching new data

Seeking assistance regarding updating data in the DataGrid component from the @mui/x-data-grid module within a React application. Specifically, I am facing challenges in refreshing the table after retrieving data from an API using react-query. Despite succ ...

Is there a way for me to store the output of an AJAX call?

One of the challenges I'm facing involves an AJAX request: $.ajax({ url: 'script.php?val1=' + value1 + '&val2=' + value2, dataType: "json", success: function (data) { var newValue1 = data[0]; ...

Checkbox in Angular FormGroup not triggering touched state

There seems to be an issue with the Angular form when checking if the form is touched, especially in relation to a checkbox element. Despite the value of the checkbox changing on click, I am seeing !newDeviceGroup.touched = true. I'm not quite sure wh ...

Nodejs restricts the user from performing the action

Currently, I am utilizing Nodejs with Expressjs and encountering an issue when trying to run the project. The connection is established successfully but when attempting to access the URL (localhost:3001/api/plans), an error appears in the console: MongoSer ...

Each time the page is reloaded, the animation's frames per second (fps

In my project, I have two main pages: 'index' and 'about'. The 'about' page includes a cool animation that you can check out here. The issue I'm facing is that when I navigate from the 'index' page to the &apos ...

A beginner's guide to integrating ng-class into a directive template using AngularJS

I have been attempting to achieve something similar to the following: template: "<div ng-if=\"successData\" ng-class=\"{ 'bounceInDown': successData == true,bounceInDown: successData == false}\" style=\"border-radius ...

Loading SVGs on the fly with Vue3 and Vite

Currently, I am in the process of transitioning my Vue2/Webpack application to Vue3/Vite. Here's an example of what works in Vue2/Webpack: <div v-html="require('!!html-loader!../../assets/icons/' + this.icon + '.svg')" ...

My jQuery Ajax seems to have a glitch, can someone help me figure out

Looking for some help with this HTML code: <section id="login"> <form> <input type="text" name="username" size="10" placeholder="username" /> <input type="password" name="password" size="10" placeholder="password" ...

"NODEJS: Exploring the Concept of Key-Value Pairs in Object

I am facing a challenge with accessing nested key/value pairs in an object received through a webhook. The object in req.body looks like this: {"appId":"7HPEPVBTZGDCP","merchants":{"6RDH804A896K1":[{"objectId&qu ...

Accessing form objects in Typescript with AngularJS

I am currently working with AngularJS and Typescript. I have encountered an issue while trying to access the form object. Here is the HTML snippet: <form name="myForm" novalidate> <label>First Name</label> <input type="text" ...

Dealing with an Ajax request that returns a file or partial HTML in the event of an error - what is the best approach?

Imagine a scenario where we are engaged in a dialogue with certain settings. Upon clicking the "OK" button in the dialogue, the settings are transmitted to a controller function through an AJAX call. This call may either yield a downloadable file or an err ...

Exploring the inner workings of self-referencing mechanics in functions

In a recent coding scenario, I encountered this situation: I attempted to define the func1() function and add several static methods to it simultaneously by passing it through the _init() function along with a hash containing properties to attach. However, ...

Generating navigation links with search queries

Embarking on the journey of incorporating pagination alongside user-defined search parameters has left me puzzled. I have a good grasp on pagination implementation without user input, but once user input factors in, confusion sets in. I find myself at a lo ...

Error: 'error' is undefined

Error Alert: The code is encountering a ReferenceError, indicating that 'error' is not defined in the following snippet: app.post('/register', function(req, res) { var hash = bcrypt.hashSync(req.body.password, bcrypt.genSaltSync(10)) ...

The PHP header() function is not properly redirecting the page, instead it is only displaying the HTML

After double checking that no client sided data was being sent beforehand and enabling error reporting, I am still encountering issues. The issue revolves around a basic login script with redirection upon validation. <?php include_once "database- ...

Just starting out with callback functions (using a callback as an argument)(Javascript)

Hello everyone, I'm a beginner here and I have a question about callback functions. Upon reading about them, I felt like I understood the concept. However, when I attempted to implement one in my code, things didn't go as planned. functio ...

What is the best way to decipher a base64 API response in AngularJs?

I'm currently facing a challenge where I have to decode the base64 encoded API response from the backend, instead of receiving it in JSON format. This is the response that I'm encountering: eyJzdGF0dXNDb2RlIjoiT0siLCJtZXNzYWdlIjoiU1VDQ0VTUyIsImR ...

Is there a way to verify HTML binding prior to setting up an AngularJS directive?

On a page where I utilized a custom select-box directive to display the Month, certain arguments are required by the directive: <custom-select-box id="month" model="month" model-required model-name="month" options="month.value ...

Animated div or fieldset featuring a multi-step form

I have recently put together a detailed step-by-step guide. Each step is wrapped in its own "fieldset" within a single .html file. To navigate back and forth, I have incorporated javascript into the process. However, as time goes on, I am noticing that th ...