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

Troubleshooting the malfunction of jQuery's change() function

There are three HTML select tags on my page. I want these three select tags to function as follows: When I change selectA, selectB should automatically update based on the selection in selectA. Similarly, when an option in selectB is created, changing se ...

Storing client time data in a database using Node.js

Just starting out with Node.js so bear with me while I learn the ropes. I successfully set up a basic TCP server using the guide here In my current project, users will connect to the server from a web browser and I'm interested in capturing the TCP ...

The JavaScript script to retrieve the background color is malfunctioning

I am currently working on developing a highlighting feature for an HTML table that will dynamically change the row colors on mouseover. Below is the code snippet I have been using, but it seems to be experiencing some issues. Any assistance would be greatl ...

Issue with document.referrer in Firefox: Unexpected behavior

I attempted to utilize the document.referrer function. It functions correctly in Google Chrome, however it does not yield the expected results in Mozilla Firefox. if (document.referrer.indexOf('stringToCheck') > 0) { //insert code here ...

Vue 3 - Compelled to utilize any data type with computedRef

Recently, I've been diving into Vue/Typescript and encountered a puzzling error. The issue revolves around a class named UploadableFile: export class UploadableFile { file: File; dimensions: Ref; price: ComputedRef<number>; ... constr ...

Add a fresh record only if it contains information and there are no existing duplicates present

Is it possible to create a note with both a title and text, under certain conditions? The title must not be empty The title cannot already exist in the system When attempting to check for duplicates within my array, the boolean value always returns true ...

What could be causing my asynchronous JavaScript/Node.js function to bypass a significant portion of the code?

Upon calling the function below: async function sql_func(){ console.log('anothertest') async () => { console.log('third test') try { await sql.connect('heres the connection data') ...

Components in React are unable to be accessed

I'm a complete beginner when it comes to React and I'm facing issues with organizing my components into separate files. The error message I encounter is: ERROR in ./src/App.js 5:0-34 Module not found: Error: You attempted to import /components/ ...

Activate modifications in a distinct column?

I've been exploring a solution to achieve a similar functionality where clicking or hovering on headings in a column brings up corresponding text in another column. My idea is to use list items with a carousel for this purpose, but I'm facing so ...

What is the most efficient way to apply a single click handler instead of using multiple click handlers for the same

Check out the project I'm currently working on by following this link: The link provided above contains a list of clickable colors available on the right side. When a user clicks on a color, the images on the left side change accordingly. Below is t ...

The issue of overflow-y not functioning properly in conjunction with ng-repeat has been observed

As indicated in this resource, setting a fixed height for the div is suggested, but it seems like it's not working with the code provided below. <div style="margin-top:0.5vh;"> <div style="height:200px;border:1px solid red;overflow:au ...

The event listener fails to function properly in asynchronous JavaScript

The reason for the error is due to the asynchronous nature of the code, where the button is not loaded yet. Is there a solution to this issue? It's difficult to explain in words but essentially, when the window is loaded, the button is not present as ...

Issue with AngularJS AJAX Request

When working with AJAX calls, how can we improve error handling to make it more meaningful? Using the template code provided may not effectively communicate the issue. What are some ways we can better understand and handle exceptions? <script> ...

Encountering a crash issue with JMeter's Selenium Sampler while attempting to click on a button with the Phantom

After building a JMeter Project, I have been utilizing the WebDriver Sampler (Selenium) to monitor response times during interactions with a particular feature on a webpage. To test my project, I have experimented with both Firefox and Chrome Driver confi ...

Angular - The argument provided is not compatible with the parameter

I encountered the following TypeScript errors in app.component.ts: Issue: Argument of type '(events: Event[]) => void' is not assignable to parameter of type '(value: Event[]) => void'. Description: Types of parameters 'events& ...

NodeJS not recognizing global variable causing it to return undefined

Can a global variable be defined in a node.js function? I wish to use the variable "ko" (declared in the getNumbers function) in other functions function getNumbers(callback) { result = cio.query("SELECT numbers FROM rooms WHERE durum='1'", ...

Instructions for appending an id to the URL of events in fullcalendar using Rails

Looking for a way to attach an ID to the URL of a fullcalendar event in a Rails application? I am using a json.jbuilder file: json.array!(@estudiante.clases) do |clase| json.extract! clase, :id json.id clase.id json.title clase.name json.start cl ...

Having trouble injecting dependencies into a Jasmine test, as I'm receiving the following error message: "$injector:unpr Unknown provider: appConfigProvider <- appConfig"

I've been working on creating a Jasmine test, but I'm having trouble with injecting dependencies declared in the 'myApp' module. When trying to inject the dependency (constant) value appConfig, I encounter the following error: Error: [ ...

Mocha struggles to locate the ID within an input field - react-native

I am attempting to retrieve the text of an input using the .text() method in Selenium. However, every time I try to locate the element, it says that the specified ID was not found. (I am working with the Input component from NativeBase, but I have also te ...

Creating a JavaScript class definition without the need for instantiation

I am looking to create an empty data class in JavaScript that can later be filled with JSON data. In C#, I would typically do something like this: class Person { string name; int age; Person[] children; var whatever; } However, when I try ...