Strange behavior observed when transclusion is used without cloning

During my experimentation with transclusion, I wanted to test whether the transcluded directive could successfully locate its required parent directive controller after being transcluded under it. The directives used in this experiment are as follows: - There is a ParentOfParent directive with transclude:true. - A Parent directive embedded within the ParentOfParent directive template. - A Child directive which requires the Parent controller and is transcluded by ParentOfParent to become a child of the Parent directive.

'use strict';
angular
    .module('angularlabApp', [
    'ngRoute',
])
    .config(function ($routeProvider) {
    $routeProvider
        .when('/', {
        templateUrl: 'main.html',
        controller: 'MainCtrl'
    })
        .otherwise({
        redirectTo: '/'
    });
});

'use strict';
angular.module('angularlabApp')
    .directive('parent', function () {
    return {
        controller: function () { },
        restrict: 'EA',
        link: function postLink(scope, element, attrs) {
            console.log('Parent Link');
        }
    };
});

'use strict';

angular.module('angularlabApp')
  .directive('parentOfParent', function () {
    return {
      template: '<div id="prnt" parent></div>',
      transclude: true,
      restrict: 'EA',
      link: function(scope, element, attrs,_,transcludeFn){
        console.log('POP Link');
        element.find('#prnt').append(transcludeFn());

      }
    };
  });


'use strict';

angular.module('angularlabApp')
  .directive('child', function () {
    return {
      template: '<div></div>',
      restrict: 'EA',
      require:'^parent',
      link: function postLink(scope, element, attrs) {
        console.log('Child Link');
      }
    };
  });


'use strict';
angular.module('angularlabApp')
    .controller('MainCtrl', function ($scope) {
});

While conducting the tests, I noticed an interesting discrepancy when using the transclusion function with and without cloning. When I use the transclusion function output without passing the cloneFn, an error occurs stating that the child directive cannot find the Parent Controller above it. [http://plnkr.co/edit/JteQpPMc6nbVNjRDHVZ2](http://plnkr.co/edit/JteQpPMc6nbVNjRDHVZ2)

However, everything works smoothly when I pass the cloneFn while using it.

This raised the question for me - is it feasible for a transcluded directive to discover the required controller after being inserted below the directive it belongs to?

Answer №1

I finally had a breakthrough in understanding the concept thanks to this insightful answer, as well as this informative article.

It became clear to me that when utilizing the output of the transclude function without passing the clone callback, the output is already compiled and marked as LINKED.

var linkedClone = $transcludeFn();

As a result of this linking process taking place beforehand, the duplicated directive automatically seeks the controller of its parent directive. However, since the copied DOM node remains detached, it fails to locate said controller.

In contrast, when receiving the copied DOM subtree through the clone callback method, as elaborated in the article:

Compile clone in child scope of directive’s scope and pass clone before calling all its linking functions

This approach allows for attaching the copied DOM subtree prior to its linking stage, thereby enabling it to successfully find the controller above it once it is incorporated into 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

What is the best way to implement the settimeout method in react?

I need assistance on how to effectively utilize the setTimeout() method in my code. Specifically, I am looking to trigger a click event on an element after a certain delay and execute a function afterwards. Here is the current implementation of my code: ...

Utilizing jQuery and Isotope for intricate filtering

My isotope instance contains elements with multiple parameters, as shown below: <element data-a="1 2 3 4 5" data-b="1 2 3 4 5" data-c="1 2 3 4 5" Filtering for an element that has A1, B2, and C3 is straightforward: .isotope({ filter: '[data-a~=1 ...

Issue with Vue-Multiselect: Unselecting a group of pre-loaded values is not functioning as expected

My code: https://jsfiddle.net/bgarrison25/tndsmkq1/4/ Html: <div id="app"> <label class="typo__label">Groups</label> <multiselect v-model="value" :options="options" :multiple="true" group-values="libs" g ...

What is the process for transmitting information via a Link in Next.js?

In my upcoming 13.1.5 version, I am faced with a challenge of sending the value of contact.name through a Link in my component. I am looking for the most effective approach to achieve this. The initial code block for the Link represents my original code. ...

What is the best way to customize the appearance of Image tags located inside SVGs, whether they are in separate files or embedded within the code

I am developing a custom SVG editor application and facing an issue with implementing a highlighted effect when an <image> element is clicked. I have successfully accomplished this for other elements like <circle> by adjusting attributes such a ...

Update the input value following a successful action

How can I update the value of an input field after a successful ajax call? I have tried the following approach but it doesn't seem to be working. The result from the alert is 80000 Here is the HTML input code: <input class="form-control" type=" ...

What is the best way to troubleshoot substrings for accurately reading URLs from an object?

While a user inputs a URL, I am attempting to iterate through an object to avoid throwing an error message until a substring does not match the beginning of any of the URLs in my defined object. Object: export const urlStrings: { [key: string]: string } = ...

Exploring nested routes with HashRouter in React

I've been working on a dashboard/admin control panel application using React, but I'm facing some challenges when it comes to handling component rendering accurately. Initially, my main App component is structured like this: <React.Fragment&g ...

I encountered a console issue that I am struggling with. It is showing the error message "TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'"

When running this code, I encountered an error in the console (TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'). Can someone help me identify where I made a mistake and provide guidance ...

Exploring the capabilities of Angular and UIGrid for fetching table information

I have been utilizing Angular along with uigrid, which is an excellent library for displaying data in a tabular format. Everything looks good when displaying the table. However, when I update an item and click on a Save button that triggers a rest service ...

Using Material UI with React hooks

I'm encountering an error while trying to incorporate code from Material UI. The error message is: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. Mismatc ...

JavaScript code to access values from a JSON object

{ "4": { "structure": "Archaeological Museum", "boxes": [{ "id": "5", "name": "Ground Cassa DEMO" }] }, "5": { "structure": ...

What is the best way to supply arguments to a generic handler function?

How can I send parameters to a generic handler in Asp.net using JavaScript/jQuery? I am working on a jQuery plugin called ajaxfileupload that utilizes a generic Handler. I need to pass certain arguments from the page using jQuery or JavaScript, such as Dy ...

Can we split the PHP Photo Gallery into a second page after displaying 12 images?

I recently developed a simple PHP photo gallery for my website that pulls data from a MySQL database. By using a while loop, I am able to display three images (from ID 1 to 3) in a single row, continuing this pattern until a total of 12 images are shown. ...

Filtering data in VueJs using Vuetify's v-tabs feature

I am currently utilizing NuxtJs, a lightweight version of the VueJS framework. My goal is to implement a data filtering functionality based on tab clicks. The objective is to display the data in alphabetical order and filter them accordingly when tabs are ...

Encountering a 404 error while making a jsonp call in Angular

I am currently working on a project running on localhost with a MySQL database. My goal is to display data from this database on a web page using a Server.js file that utilizes Express and NodeJS. var express = require("express"); var mysq ...

Why does React / NextJS throw a "Cannot read properties of null" error?

In my NextJS application, I am using useState and useEffect to conditionally render a set of data tables: const [board,setBoard] = useState("AllTime"); const [AllTimeLeaderboardVisible, setAllTimeLeaderboardVisible] = useState(false); const [TrendingCreat ...

What are some ways to optimize the efficiency of handling a sizable JSON object in React Native?

I am currently developing an application using React Native and have encountered significant slowdowns during transitions when loading more data. I am exploring alternative app structuring methods to prevent these performance issues, especially as the JSON ...

Writing a function to determine if an HTML element is present

Is there a way to create a function that checks for the existence of an element with a specific id? I have a list of IDs stored in an array: let CartArray = ["cart-0", "cart-1", "cart-2", "cart-3"]; This is the Java ...

Running various callbacks consecutively from an array in JavaScript

I have a series of functions in an array, each one calling a callback once it's finished. For example: var queue = [ function (done) { console.log('Executing first job'); setTimeout(done, 1000); // actually an AJAX call ...