The nested directive link function failed to execute and the controller was not recognized

Apologies in advance for adding to the sea of 'mah directive link function isn't called!' posts on Stack Overflow, but none of the solutions seem to work for me.

I have a directive named sgMapHeader nested inside another directive called sgMap. sgMapHeader is not always present, so I append it and compile at sgMap's link time. Both directives share a controller. You can view a simplified version of my issue in this JSBin example.

In an ideal scenario, I would expect two things:

  1. The inner directive's link function should be executed, logging 'hi there' to the console.
  2. If I click on the 'hi there' text, 'hold' should be logged as well.

Unfortunately, neither of these expectations are met. I have tried adjusting the scope in different ways, but nothing seems to make a difference. Can anyone point out what I might be missing?

Answer №1

The sgMapCtrl variable is not declared

controllerAs:'sgMapCtrl',

Please ensure that sgMap directive is properly defined

The following code snippet has been effective for me:

MODIFY

angular.module('map.directive', [])
.directive('sgMap', ['$compile', function($compile) {
    return {
        replace: false,
        template: '<section class="md-whitespace-2"></section>',
        scope: {
            header: '=header',                 // Whether to show the header. (bool)
        },
        restrict: 'E',
        controllerAs:'sgMapCtrl',
        controller: [function() {
            this.changeAction = function(action) {
                console.log(action);
            };
        }],
        link: function(scope, element, attrs) {
            // Add header?
            if (scope.header) {

                $compile('<sg-map-header></sg-map-header>')(scope, function(cloned, scope) {
                    element.append(cloned);
                });
            }
        }
    };
}])
.directive('sgMapHeader', [function() {
    'use strict';

    return {
        replace: false,
        restrict: 'E',
        require: '^sgMap',
        scope: false,
        template: '<div ng-click="sgMapCtrl.changeAction(\'hold\')">hi there</div>',
        link: ['$scope', 'sgMapCtrl', function($scope, sgMapCtrl) {
            sgMapCtrl.changeAction('<div>hi there</div>');
        }]
    };
}]);

angular.module('app', ['map.directive']);

Answer №2

First, make sure to append to the DOM before compiling.

        // Should we include a header?
        if (scope.header) {
            var $header = angular.element('<sg-map-header></sg-map-header>');
            element.append($header);
            $compile($header)(scope);
        }

When compiling sgMapDirective, it must be a child of sgMap in order for the compile process to work correctly. Otherwise, the compilation will not find sgMapDirective within the parent elements because it only exists in memory and not in the DOM.

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

Transfer numerical values from PHP to JavaScript using individual files

What is the best way to pass variables from PHP to JavaScript when they are in separate files? Is it possible to achieve this without using AJAX, or is AJAX necessary for this task? If AJAX is required, how can I implement it? test.php <?php $a = 5; $ ...

What could be causing certain javascript functions to not work properly?

Currently, I am using JavaScript and AJAX to validate a registration form. The functions restrict(elem) and checkusername() are both working as intended. When the AJAX passes the checkusername variable to PHP, it checks if the username exists and displays ...

Using a jQuery dialog to launch a popup window specifically optimized for Safari browsers

I recently encountered an issue with my plain JavaScript function that opens a pop-up window. It functions perfectly in Chrome and Firefox, but I faced difficulty in Safari due to the default popup blocker preventing the page from opening without any err ...

What is the process of encrypting a password using AngularJS on the client side, transferring it securely to the server through ExpressJS, and then decrypting it on the server

Looking for a simple method to encrypt a password on the client side using angular.js, send it to the server with express.js, and then decrypt it? While there are libraries like angular-bcrypt and similar ones in nodeJS, they may not be suitable as they ma ...

I am able to retrieve JSON data from the server using Angular, however, I am facing an

I have successfully accessed JSON data from the server, but I am struggling to display it properly. Currently, I can only show all models, but I want to display specific data. My template <!DOCTYPE html> <html> <head lang="en"> ...

Rotate Chevron icon downwards on mobile devices in a Multilevel Dropdown Bootstrap 4

Bootstrap 4 is being utilized for my current project, I am looking to modify the rotation of the chevron icon in a multi-level dropdown menu specifically on mobile devices when the parent link is tapped, Here is the code snippet for the multi-level dropd ...

Is there a way to retrieve the objects generated by DirectionsRenderer on Google Maps V3?

Is there a simple method to access the objects and properties of the markers and infowindows that are generated by the DirectionsRenderer? (such as the "A" and "B" endpoints of the route) I want to swap out the infowindows for the "A" & "B" markers wi ...

Step-by-step guide on building a personalized rxjs operator using destructured parameters

I am in the process of developing a unique RxJS filter operator that requires a destructured array as a parameter. Unfortunately, TypeScript seems to be throwing an error related to the type declaration: Error TS2493: Tuple type '[]' with a len ...

Encountering a node.js issue

Hi there, I keep encountering this error message. Can someone explain what it means? I'm not very skilled in coding, so I would appreciate any assistance :) Best regards logon fail: 65, sessionID: 6343803 events.js:85 throw er; // Unhandled & ...

How to target the last child in Flexbox using CSS order property

Is there a way to correctly detect the last child after rearranging divs using flex order? Even though I have set the order in the CSS, it is still recognizing the last child based on the DOM tree. Since the items are dynamic, we can't rely on nth-chi ...

What is the best way to display data in a React application depending on a boolean value?

Being new to React and JavaScript, I am currently struggling with boolean logic. I have a function called Profile which includes two constant methods that each return different data. function Profile(props) { const returnNormalProfile() const return ...

React's Conditional Rendering

Let's imagine having these initial conditions: this.state = {plans: [], phase: 'daybreak'} along with a dynamic JSON object fetched from an API containing various schedules that may change periodically, for example: plans = {"daybreak": " ...

The art of controlling iframe elements with jquery

I've been researching various topics related to this issue, but I'm still unable to achieve the desired outcome. Currently, I am embedding an iframe within an HTML document like so: <iframe class="full-screen-preview__frame" id="nitseditpre ...

Choosing multiple images by clicking on their alternative text with jQuery

I am currently working on a project that involves clicking on a thumbnail to enlarge the image and display its name (alt) below it. I have made progress, but there seems to be an issue where only one image is displayed no matter which thumbnail I click on. ...

Error encountered when injecting factory into AngularJS controller

Starting my journey with Angular, I am currently working on my very first angular app. The main goal is to fetch data from an external source and make it accessible to all controllers on my portfolio webpage. This is the structure of my HTML: <!DOCTYP ...

Error: The JSON in app.js is invalid due to the unexpected token "C" at position 0

When I try to run this code snippet, I sometimes encounter an error message that says: SyntaxError: Unexpected token C in JSON at position 0. function fetchData(user_country) { fetch(`https://covid19-monitor-pro.p.rapidapi.com/coronavirus/cases_by_day ...

What is the best way to show input choices once an option has been chosen from the 'select class' dropdown menu?

When it comes to displaying different options based on user selection, the following HTML code is what I've been using: <select class="form-control input-lg" style="text-align:center"> <option value="type">-- Select a Type --</opti ...

Clicking on a button in HTML to open a JavaScript file

As a beginner in HTML and JavaScript, I am looking for a way to open a JavaScript file when the onclick event of a button in my HTML file is triggered. Can anyone provide me with guidance on how to achieve this? Thank you in advance. ...

Cross-Origin Resource Sharing (CORS) Issue: How Angular.JS, Node.JS, and

Encountering problems retrieving data from a http post request to my API. Seeing the following error message: XMLHttpRequest cannot load (URL to API here). No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin &ap ...

Tips for seamlessly incorporating a fresh ionic theme into your current ionic application

I am currently developing a project with Ionic v1 and Angular 1, using the basic Ionic UI. While browsing through the Ionic marketplace, I found several interesting themes. Can someone guide me on how to implement a new Ionic theme into my existing appli ...