Dynamically inserting templates into directives

I've been attempting to dynamically add a template within my Angular directive. Following the guidance in this answer, I utilized the link function to compile the variable into an HTML element.

However, despite my efforts, I haven't been successful in getting it to work.

This is the snippet of my HTML:

<spinners></spinners>

And here's my directive code:

app.directive('spinners', function() {
    return {
        restrict: 'E',
        link: function(scope, element, attrs) {
            var spinkit = ["<rotating-plane-spinner></rotating-plane-spinner>", "<double-bounce-spinner></double-bounce-spinner>", "<wave-spinner></wave-spinner>", "<wandering-cubes-spinner></wandering-cubes-spinner>", "<pulse-spinner></pulse-spinner>", "<chasing-dots-spinner></chasing-dots-spinner>", "<circle-spinner></circle-spinner>", "<three-bounce-spinner></three-bounce-spinner>", "<cube-grid-spinner></cube-grid-spinner>", "<word-press-spinner></word-press-spinner>", "<fading-circle-spinner></fading-circle-spinner>"];
            var spinner = spinkit[Math.floor(Math.random() * spinkit.length)];
            var el = angular.element(spinner);
            compile(el.contents())(scope);
            element.replaceWith(el);
        }
    };
});

In order to display spinners randomly on my loading page using Angular-SpinKit from here, I decided to implement this method. While using a single directive of spin kit directly works fine, implementing the above approach does not show anything on my HTML page.

Answer №1

It seems like the issue lies in this specific line of code: compile(el.contents())(scope);

The correct syntax should be using $compile instead of compile, as it is a service that needs to be injected into the directive.

Therefore, the corrected lines are: $compile(el.contents())(scope); And

app.directive('spinners', function($compile) {

app.directive('spinners', function($compile) {
    return {
        restrict: 'E',
        link: function(scope, element, attrs) {
            var spinkit = ["<rotating-plane-spinner></rotating-plane-spinner>", "<double-bounce-spinner></double-bounce-spinner>", "<wave-spinner></wave-spinner>", "<wandering-cubes-spinner></wandering-cubes-spinner>", "<pulse-spinner></pulse-spinner>", "<chasing-dots-spinner></chasing-dots-spinner>", "<circle-spinner></circle-spinner>", "<three-bounce-spinner></three-bounce-spinner>", "<cube-grid-spinner></cube-grid-spinner>", "<word-press-spinner></word-press-spinner>", "<fading-circle-spinner></fading-circle-spinner>"];
            var spinner = spinkit[Math.floor(Math.random() * spinkit.length)];
            var el = angular.element(spinner);
            $compile(el.contents())(scope);
            element.replaceWith(el);
        }
    };
});

Answer №2

Give this a shot:

app.directive('spinners', function($compile) {
return {
    restrict: 'E',
    link: function(scope, element, attrs) {
        var spinkit = ["<rotating-plane-spinner></rotating-plane-spinner>", "<double-bounce-spinner></double-bounce-spinner>", "<wave-spinner></wave-spinner>", "<wandering-cubes-spinner></wandering-cubes-spinner>", "<pulse-spinner></pulse-spinner>", "<chasing-dots-spinner></chasing-dots-spinner>", "<circle-spinner></circle-spinner>", "<three-bounce-spinner></three-bounce-spinner>", "<cube-grid-spinner></cube-grid-spinner>", "<word-press-spinner></word-press-spinner>", "<fading-circle-spinner></fading-circle-spinner>"];
        var spinner = spinkit[Math.floor(Math.random() * spinkit.length)];
        var el = angular.element(spinner);
        element.replaceWith(el);
        $compile(el)(scope);

    }
};
});

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

Steps for installing an npm package from a downloaded folder

In the past, I had a method of installing an npm project from Github that involved using git clone followed by npm install. git clone http...my_project npm install my_project Instead of manually copying the contents of my_project to my local node_modules ...

Struggling with sending a post request in Node.js as the response always returns with an empty body

Here is the structure of my project And this error pops up when I run my program using npm run dev command I'm working on a basic webpage where users can input their name, email, and job details. I then try to insert this information from the HTML fo ...

Strange behavior observed when resizing objects in Three.js WebGl

Everything was going smoothly with my code until I decided to enable WebGL. It seems that the function responsible for resizing my object every frame rate stopped working. function animate(){ window.requestAnimationFrame(animate); s.setPositio ...

Issue with camera boundaries in Three.js when using EffectComposer with an orthogonal camera is currently presenting inaccuracies

In reference to a previous question on Three.js, I have successfully created a scene with a "minimap" using an orthogonal camera rendering into a viewport. The minimap is displayed properly in the standard renderer. Now, I wanted to add postprocessing eff ...

Is there a risk of overloading the server and browser by making constant AJAX calls at regular intervals?

I am in the process of creating a website that requires notifications. I want to use AJAX to continuously check for updates in my database where notifications are stored at regular intervals. My concern is, with multiple users all accessing the AJAX call ...

Using jQuery to trigger an action when a user clicks on a regular audio element

Is there a way to detect a click on the default audio element of a browser using jQuery? I'm having trouble getting it to work in Chrome. $('audio').click(function(){ alert("You have clicked on an audio player"); }); <script ...

angularjs bootstrap typeahead result offspring

I have a situation where my input is bound to the object line.product, but the typeahead function is returning pairs of products and suppliers. The current code ps.product as ps.product.code for ps in getProductSupplierRefList($viewValue) does not return t ...

Setting a cookie within an Angular interceptor

My angular interceptor function includes a request object. intercept(req: HttpRequest<any>, next: HttpHandler) { return next.handle(req); } I am looking to set my token in the request cookie under the name my-token. How can I achieve this? I ...

What is the methodology behind incorporating enumerations in typescript?

I've been curious about how typescript compiles an enumeration into JavaScript code. To explore this, I decided to create the following example: enum Numbers { ONE, TWO, THREE } Upon compilation, it transformed into this: "use strict ...

Ways to incorporate a unique debounce technique where the function is only executed every nth time

const _debounce = (num, fn) => { //implementation goes here } const originalFunction = () => { console.log('fired') } const _callFunc = () => _debounce(2, originalFunction) _callFunc() //The originalFunction does not run _callFun ...

What is the easiest way to pass a chosen value to PHP?

My goal is to dynamically display photos based on the selected album without refreshing the entire page. Here is my current script: <script type="text/javascript"> function replaceContent(divName, contentS) { document.g ...

The table is unable to properly display the array data

My code includes an AJAX function that sends a GET request to an API and receives data in the format shown below: { "firstname": "John", "lastname": "Doe", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6 ...

How can I trigger a method after the user has finished selecting items in a v-autocomplete with multiple selection using Vuetify?

After multiple selections are made in a v-autocomplete, I need to trigger a method. However, the @input and @change events fire after each selection, not after the full batch of selections. Is there an event that triggers when the dropdown menu closes? Al ...

SheetJS is experiencing difficulties parsing dates correctly

Need help exporting an HTML table to an Excel file using the SheetJS library. Here's my code snippet: var table = document.getElementById("tableToExport"); var ws = XLSX.utils.table_to_sheet(table, { sheet: "Raport Odorizare", da ...

Effortless sliding panel that appears on hover and vanishes when mouse is moved away

I am in the process of creating a menu for my website that utilizes linkbuttons which trigger additional linkbuttons to slide down upon hover. The desired effect is a smooth sliding panel that appears when hovering over the linkbutton, and disappears when ...

The application is unable to recognize the CSS file

I am facing an issue where the design of my app is not displaying, even though the CSS file is located in the same folder. I'm unsure about what mistake I might have made! import React from 'react'; import classes from './Burger.css&ap ...

What is the best way to transfer the text from an input field into a paragraph when a button is

For a school project, I am developing a website focused on time management. My goal is to create an input text box that, when the "add task" button is clicked, transfers the text inside it to a paragraph or p2 element and then moves the input field down. ...

Text that appears automatically in an input field

I've searched high and low, but I just can't seem to find a solution that works for me. What I need is a way to automatically populate a HTML text field with default text when the page loads. This default text should ideally be a PHP variable and ...

Confirm that two Angular form fields contain different content

My angular form has two fields labeled Location A and Location B. I am looking to create a directive that can compare these two fields and validate them accordingly, while also styling the valid or invalid field based on whether both locations are the same ...

What is the best way to display input fields only if the previous input has a valid value?

My challenge involves creating a form with 3 to 10 text input fields. Initially, the form will display only 3 inputs (minimum). I am looking for an efficient way to dynamically show additional input rows as each previous row is filled out with a valid val ...