Dynamically loading custom directive by assigning it to the controller's scope

I need help with dynamically loading my custom directive when a button is clicked. I am making an AJAX call to retrieve the directive's HTML and then compiling the response to assign it to a controller scope variable. However, the corresponding template of the custom directive is not displaying correctly. Can someone assist me with this issue?

Below is the code snippet that demonstrates the problem:

HTML file:

<body ng-app="sampleApp" ng-controller="DemoController as DemoCtrl">
 <div ng-bind-html="test">
 <md-button class="md-raised md-primary" ng-click="DemoCtrl.getDirective()">Click to get directive</md-button>
</body>

Module and Controller/Directive:

angular.module('sampleApp',['ngMaterial'])

        .directive('test',function(){
            return {
                restrict: 'E',
                template: '<B>Hello World</B>'
            };
        })

        .controller('DemoController', function($compile,$scope,$sce) {
            var vm = this;
            vm.getDirective = function(){
                //Service call to retrieve the directive HTML (e.g., <test></test>)
                var directiveCode = $compile("<test></test>");
                var directiveHTML = directiveCode($scope);
                $scope.test = $sce.trustAsHtml(directiveHTML);
                $scope.$apply();
            }
        });

Answer №1

Give this a shot

angular.module('exampleApp',['ngMaterial'])

        .directive('tryme',function(){
            return {
                restrict: 'E',
                template: '<strong>Greetings Earthlings</strong>'
            };
        })

        .controller('TestController', function($compile,$scope,$sce) {
            var app = this;
            app.fetchDirective = function(){
                //Fetching the directive through a service call. Received response as <tryme></tryme>
                var renderedCode = $compile("<tryme></tryme>");
                var resultingHTML = renderedCode($scope);
                console.log(resultingHTML.html());
                $scope.sample = $sce.trustAsHtml(resultingHTML.html());
                //$scope.$apply();
            }
        });

Answer №2

Big thanks to @Awolf and @wasiq for your assistance. The code snippet you provided worked perfectly.

The problem I encountered was due to setting the directive's template to the controller scope before the AJAX call had finished. This resulted in the directive's template not appearing in the DOM. I have now corrected this by moving the assignment of the scope variable inside the success block, resolving the issue.

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

Encountering the `undefined is not a function` error message when trying to map the response data from an API call within a

While working with an API, I am saving the result in a state called shift and here is the outcome: [ { "id": 123, "status": "created", "expected": { "end_time": " ...

Keep track of the $index value when using ng-repeat in AngularJS

I am facing a minor issue where I need to save the $index value in order to reuse it in the next ng-repeat. Here's the situation: I have created an object array that matches the size of my JSON array. This is how my object array looks like: $scope ...

Guide to changing a promise into a float using protractor

Currently, I am developing end-to-end tests with protractor and I need to verify the accuracy of certain calculated values on a page. It seems like a straightforward task: var variable1 = element(by.binding('variable1')); var variable2 = element ...

Discovering the data from every input field using jQuery

So, I've created a program that starts with one input field. By pressing the plus button, it adds new input fields with different IDs. When I press calculate, I want to save all the input field values into an array. I attempted using a for loop with . ...

Vue.js global event issue

Recently, I encountered an issue with the following code: <component-one></component-one> <component-two></component-two> <component-three></component-three> Specifically, component-two contains component-three. My cu ...

Typescript method fails to compile due to an indexing error

Imagine you're trying to implement this method in Typescript: setResult(guId: string,fieldname: string, data:Array<UsedTsoClusterKey>) { let octdctruns: OctDctRun[] = [...this.octDctRuns]; const index = octdctruns.findIndex((o) => o.guid ...

Ways to properly exit a function

What is the best way to pass the apiKey from the createUser function in User.ts to Test.ts in my specific scenario? User.ts interface User { url: string, name: string, } class User{ async createUser( user: User ):Promise<void> { le ...

jQuery Mobile dual range slider functioning but experiencing some glitches

I successfully created a dual range slider by stacking two sliders on top of each other using the jQuery Mobile framework. In addition, I have implemented JavaScript to ensure that the left thumb does not exceed the right one. However, I have encountered ...

Move a div smoothly to fill the entire screen starting from its current position

I am looking to make a div expand to full screen upon being clicked, similar to the functionality demonstrated in this Fiddle js link here My goal is to animate the expansion from its current position. When I click on the box, I want it to grow as if expa ...

The jQuery plugin fails to display properly when used in conjunction with AngularJS

Currently, I am working on a tabs application and have implemented an angularJS directive to utilize the jquery tabs plugin. Unfortunately, I am facing issues with the view not updating properly and the tabs not being displayed as expected. Here is a link ...

Is there a way to invoke C# code within a Protractor test?

Is it feasible to leverage C# in executing certain aspects of my Protractor unit tests? The rationale behind this is rooted in the need to extract data from a database and juxtapose it against anticipated outcomes residing in text files. Given the complex ...

Utilizing the power of $.ajax() to parse through an XML document

I have a query about working with a large XML file containing 1000 nodes. Here is the code snippet I am using: $.ajax({ type: "GET", cache: false, url: "someFile.xml", ...

What is a method to omit elements within a nested child element from a selection without relying on the children() function

Here is an example of an element: <div id="foo"> <a href="#" class="some">click me</a> <div id="bar"> <a href="#" class="some">click me too</a> </div> </div> I am facing the challenge of selectin ...

Is it possible to create two sticky headers with varying heights?

Looking to develop a website featuring two sticky elements at the top of the page - a sticky header and a sticky toolbar. Utilizing Bootstrap's Affix for the toolbar and sticky.js for the header. Encountering an issue where setting {topSpacing:0} cau ...

``There seems to be a problem with the module execution

Currently, I am working on an AngularJS application where I need to ensure that the app only boots up once all data is fully loaded. To achieve this, I am trying to make requests in JSONP format and loading the $resource module using a .run statement. Bel ...

The functionality of my Javascript code is restricted to a single element within a Python embedded for loop in Django2

My Python for loop is iterating through these HTML template cards, each accompanied by JavaScript. However, I'm encountering an issue where the JavaScript only seems to work on the first element (specifically, it's meant to retrieve the seeked po ...

Disabling a button based on the result of a database query

Is there a way to dynamically enable or disable a button based on the result of a database query in JavaScript? I have managed to display an error message (with id="error") depending on the result, but toggling the button (with id="generate") doesn't ...

Issue encountered when attempting to remove items from Redux store with onClick event

My goal is to delete a specific object from an array in my store. I have a delete item function that successfully removes objects, but I am struggling to make it work with a button that is rendered with each object using map. Here is my component: import ...

Creating a two-column grid layout using Bootstrap 4 is a simple and efficient process. Let's see how

I've been struggling to get this to display side by side in a two-column grid. Even after following Bootstrap tutorials, I can't seem to make it work. Check out the code below: <div class="row"> <div class="col-md-8 ...

How to get the clean URL in AngularJS without any parameters using $location

One issue I'm facing is related to the URL structure of my application. It currently looks like this: "http://host:port/mySystem?x.system" The addition of x.system in the URL was necessary due to a legacy application requirement, but now I need the U ...