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

Can the repeated use of AJAX function calls at regular intervals adversely affect the speed of the application?

On a specific page of my application, I have been using an AJAX function continuously as shown below: <script type="text/javascript"> $(document).ready(function(){ setInterval(function() { $.ajax({ ...

The Node.js server delivers a different object to the client

I'm facing an issue while trying to send an object from the client to a Node.js server. Here is my Ajax call: $.ajax({ url: config.api.url, type: config.api.method, contentType: config.api.contentType, // application/x-www-form-urlencoded; cha ...

What could be the reason for Jest flagging CSS as untested instead of identifying untested functions?

While working on my vue3 project and writing tests with jest, I have encountered an issue where jest is incorrectly marking the CSS within several single file components as untested, even though it doesn't need to be tested. Moreover, its assessment ...

Automatically retrieve the generated PDF file upon completion (Node.js and Express)

I've been utilizing the node module html-pdf to seamlessly convert my HTML into PDF format. The conversion process goes smoothly, but I'm encountering difficulties when it comes to downloading the file once it's been generated. Below is the ...

Which API is utilized by duojs for its JavaScript modules?

I am currently utilizing duojs, a front-end web development tool similar to browserify or component. With duojs, you can directly import css and js from the file itself without any external package manifests. While I'm trying to figure out how to wri ...

The scripts are mistakenly interpreted as stylesheets, but are actually being transferred with the MIME type text/html

Encountering two console warnings while using Chrome: Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://domain/". domain/:11 Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://domain/". ...

Does the require function in nodejs have any connection to the package.json file?

If 'random_module' is included in the list of dependencies in my package.json file, can I use the code var rm = require("random_module"); to access it? Essentially, does the argument for require function apply to any module listed under the depen ...

Interested in incorporating dynamic calendar entries in ASP C#?

Here is the code snippet I utilized: <script> var count = 1; var limitValue = 3; function addNewInput(sectionName) { if (count == limitValue) { alert("You have reached the limit of adding " + count + " inputs"); ...

Is it possible to change text dynamically with an input box using JavaScript?

Is there a way to use JavaScript to create two input boxes for text replacement? Instead of constantly editing code to replace different text, I am looking for a simple user interface with Input Box A, Input Box B, and a button. The first input box will ...

Developing a unique JavaScript object by extracting information from a jQuery AJAX response

Is there a recommended approach for creating a custom JavaScript object that contains data retrieved from a jQuery AJAX request? I'm considering two methods, but unsure which is the most appropriate. The first method involves including the AJAX reques ...

Tips for pinpointing parent elements within a group of various sub child elements

CSS - <div class="windows" id="window'+divCount+'"> <p id="windowName'+divCount+'"></p> <p id="para'+divCount+'">Source</p> </div> <div cla ...

efforts to activate a "click" with the enter key are unsuccessful

I'm attempting to enhance user experience on my site by triggering the onclick event of a button when the enter key is pressed. I've tried various methods below, but all seem to have the same issue. Here is my HTML (using Pug): input#userIntere ...

transfer chosen data from a text box to a dropdown menu

Looking for: I am in need of a feature where users can input a movie title in a textbox and upon clicking the "move to selectedlist" button, the entered movie title should be added to a dropdown list that displays all the movies selected by the user. Addit ...

Transmitting POST form information from an AngularJS client to an Express/Node.js server

I am currently facing an issue where the data from my AngularJS form is not reaching the Express server, despite the client function executing successfully. I suspect there might be a problem with the URLs being used. Snippet from my AngularJS controller: ...

The swf file doesn't stretch to fit the window when the height is set to 100%

Struggling with creating a flash recorder controlled by JavaScript? Trying to get the flash to fill the browser window but disappearing when setting height or width to 100%? Where am I going wrong? <div id="flashrecorder"> <object wmode="trans ...

Wait for the record to be inserted before refreshing the screen in AngularJS using C# WCF

I am currently delving into AngularJS and constructing a webpage that features a history table. As soon as an action occurs, a database entry is created using $http.post. Subsequently, I aim to retrieve the data from the database and showcase it in the tab ...

What is the best way to switch the CSS class of a single element with a click in Angular 2

When I receive data from an API, I am showcasing specific items for female and male age groups on a webpage using the code snippet below: <ng-container *ngFor="let event of day.availableEvents"> {{ event.name }} <br> <n ...

Issue encountered while attempting to adjust a date (the modification was incorrect)

I am currently working on developing a calendar feature using Angular. Part of this project involves implementing drag and drop functionality to allow users to move appointments from one day to another. However, I have encountered a strange issue. When at ...

The error message encountered is "Uncaught (in promise) Error: Unable to access attributes of an undefined object (reading 'launch')."

I am currently learning electron.js by developing a basic application that extracts information from a website. However, I am encountering a frustrating and annoying error. Here is the folder structure of my project The following code snippet represents ...

Efficiently styling table Spans with styled components in React

Can anyone help me with a frustrating CSS problem I'm facing? I am trying to render these tags as spans, but they are not separating properly as shown in the image below. They appear stuck together and I can't figure out why. I am using styled co ...