Changing the templateUrl of a directive on the fly using the controller

How can I dynamically pass the templateUrl for the app_modal directive from the "ServerController" controller to allow for different templates for different modals? I have included the URL as an attribute in the "app-modal" tag used in the server_group.html view and am returning that URL from the templateUrl property of the directive. However, I encounter the following error:

TypeError: Cannot read property 'protocol' of undefined
at urlIsSameOrigin (http://localhost/js/:30578:17)
at $http (http://localhost/js/:24316:23)
at Function.$get.$http.(anonymous function) (http://localhost/js/:24533:18)
at compileTemplateUrl (http://localhost/js/:23130:13)
at applyDirectivesToNode (http://localhost/js/:22755:24)
at compileNodes (http://localhost/js/:22354:15)
at compileNodes (http://localhost/js/:22366:15)
at compile (http://localhost/js/:22287:15)
at compile (http://localhost/js/:38714:15271)

Directive for Modal -

angular.module("app")

    .directive("appModal", function() {
        return {
            restrict: "E",
            replace: true,
            scope: {
                modal: "=modalBody"
            },
            templateUrl: function(element, attrs) {
                return attrs.templateUrl;                  
            }                
        };

    });

Controller -

function ServerController($scope) {

    $scope.confirmDelete = {

        body: "Are you sure you want to delete?",
        primaryBtn: "Delete",
        cancel: "Cancel",
        templateUrl: "pages/DRaaS/app/ServerGroup/partials/app_modal.html"

    };

}

Html -

<app-modal modal-body="confirmDelete" templateUrl="pages/DRaaS/app/ServerGroup/partials/app_modal.html"><app-modal>

Answer №1

During the execution of the templateUrl function, the scope is not accessible and the attribute values are still not interpolated. For example:

<foo param="{{a}}"></foo>

In this case, within the templateUrl, you will receive the string "{{a}}" for attrs.param instead of the value of $scope.a.

To address this issue, it is recommended to pass the template URL as a variable (preferably through an isolated scope) to the directive. Within the directive, you can easily utilize ng-include bound to that variable.

.directive("appModal", function() {
  return {
    restrict: "E",
    replace: true,
    scope: {
      modal: "=modalBody",
    },
    template: '<div ng-include="modal.templateUrl"></div>'
  };
});

The usage would then be as follows:

<app-modal modal-body="confirmDelete"></app-modal>

And in the controller:

$scope.confirmDelete = {
  // other properties,
  templateUrl: "path/to/template.html"
}

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

Adapting the column width to display or hide content with CSS styling

I have a row with 2 columns. The left column contains my main content and the right column is a chatroom. I would like users to be able to minimize and open the chatroom, which I already know how to do. However, when the chatroom is open, I want the left ...

Choose the text by clicking on a button

I currently have: <span class="description">Description 1</span> <button class="select">Select!</button> <span class="description">Description 2</span> <button class="select">Select!</button> <span clas ...

Optimizing the particle rendering speed for HTML5 <canvas> elements

Currently conducting an experiment to enhance the maximum particle count before frame-rates begin to decrease in HTML5 Canvas. Utilizing requestAnimationFrame and employing drawImage from a canvas as it appears to be the most efficient method for image re ...

Transform the C# DateTime to LocalTime on the client side using JavaScript

Utilizing the Yahoo API on my server to retrieve currency information can be done through this link: Yahoo Currency API This API provides me with both a Date and a Time, which I'd like to combine into a single DateTime object. This will allow me to e ...

I'm encountering a "confirm" error within the data table. Any suggestions on how to resolve this issue?

When I try to use two datatables columns in confirm, an error occurs when the text 'do you want cancel?' is displayed. The issue seems to be with the text itself and not the code. How should we go about fixing this problem? This is my current cod ...

Creating PDF documentation in a JavaScript architecture MVC framework, specifically utilizing Backbone.js

In my project, I have implemented a Backbone Marionette single page application that interacts with a RESTful API backend using RoR. I am interested in providing users with the ability to export a PDF report that includes specific rendered views, regions, ...

Tips for incorporating MUI into your Redwood JS project

Trying to integrate MUI into Redwood JS has been a challenge for me. I attempted to run the following command in the project directory: yarn add @mui/material Unfortunately, an error message appeared in the console stating: An error Running this command w ...

Error in Laravel: The source map for js/app.js could not be located, request failed with a status code 404

I recently started using laravel and keep encountering the following error message in the browser console: Source-Map-Error: request failed with status 404 Resource-Address: Source-Map-Address: popper.js.map I'm struggling to pinpoint the ...

Calculating the total price of items in a shopping cart by multiplying them with the quantity in Vue.js

I am currently working on enhancing the cart system in Vue.js, with a focus on displaying the total sum of product prices calculated by multiplying the price with the quantity. In my previous experience working with PHP, I achieved this calculation using ...

Acquire the item that is found in every array (Javascript)

In my data, I have multiple arrays like the following: { names: [0, 1, 2], gender: [2, 5, 1], boolean: [7, 2, 1, 6] } Is there a way to extract the value that appears in all arrays? For example, how can I retrieve the value 1 since it is prese ...

Retrieve the value of a duplicated object key from a JSON and replace it with just one unique value

In my current project, I am faced with the challenge of extracting duplicate object keys' values from a JSON dataset and replacing them with only one value. My goal is to ultimately return these unique key-value pairs as an array. NOTE: This data has ...

After the main page is loaded, the div will be dynamically populated with HTML content. How can we confirm that it has finished

I recently took over a project where a page loads and then code attached to that page populates a div with dynamically generated html – essentially filling an existing div with a string of html elements. Within this string are links to images, among oth ...

Troubleshooting undefined results when dynamically loading JSON data with $scope values in AngularJS

My input field is connected to the ng-model as shown below. <div ng-app="myApp" ng-controller="GlobalCtrl"> <input type="text" ng-model="FirstName"> {{FirstName}} </div> In my controller, console.log $scope.FirstName shows m ...

Node.js and Express: ensuring completion of asynchronous operation before responding to HTTP request

Imagine there is a callback function set up for an HTTP GET request, structured like this: router.get('/latestpost', function(req, res, next) { var data = new FbData(); get_latest_post (data); get_post_image (data); res.json(da ...

Mastering the art of tab scrolling in VueJS using Bootstrap-vue

Currently, I am working on a VueJS project that utilizes bootstrap-vue. The issue I am facing is that when rendering a list of tabs, it exceeds the width of its parent container. To address this problem, I aim to implement a solution involving a set of but ...

Discovering WebElements nested within other WebElements using WebdriverJS

Looking at this HTML structure <div> <div> <p class="my-element"></p> </div> <div> <div> <div> <p class="the-text"> I want to retrieve this text</p> </div> </div> <div> ...

How can Next-auth handle redirection for 401 errors?

Currently, I am utilizing Next-auth in combination with rtk query. My goal is to configure the application so that whenever a request results in a 401 unauthorized error, the page will automatically redirect to the login page. How can this be achieved? I ...

"Unexpected compatibility issues arise when using TypeScript with React, causing errors in props functionality

Just the other day, my TypeScript+React project was running smoothly. But now, without making any changes to the configurations, everything seems to be broken. Even rolling back to previous versions using Git or reinstalling packages with NPM does not solv ...

Guide to incorporating all template partials dynamically while leveraging a module in AngularJS

For several modules I have in my application, there is a need to load template partials whenever the module is used. These files are stored in a folder named partials inside each module subfolder. Starting from meanjs, I store these partials in public/modu ...

What is the best way to pass an array through router navigate function?

I've searched for a solution in other questions, but nothing has helped me... My goal is to redirect to a URL like this: this.router.navigateByUrl('/products'); I want to pass an array and retrieve it in the component with the active link ...