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

I seem to be stuck in an endless loop within React and can't find a way to break free

Currently, I am utilizing the useState() function along with an array errors[] as part of the state and a function setError() to pass the useState() function to child elements for calling purposes: const [errors, setErrors] = useState([]); //-------------- ...

Top technique for creating a unique cursor image for a website

I'm looking for the most efficient way to create a custom cursor image for my CSS/HTML5 website without using Flash. Ideally, I would like to implement this using CSS rather than resorting to Javascript. If Javascript is necessary, I want to know whic ...

Struggling to employ JavaScript events when submitting a form to verify the fields

My goal is to create a form with fields that have real-time validation using JavaScript. I have achieved this by utilizing Java events in the following way: Text field onkeyup: This event sends a request to check for errors in the field every time a key ...

How can I organize the selected options from a select2 form element using a basic sorting method?

I am utilizing select2 by ivaynberg and encountering an issue with the data arrangement upon submission. Is there a method to have the results in the form submit data reflect the order in which they were selected in the select2 element, without relying on ...

Are there any ways to pass an onClick function to a controller in React?

To prevent duplicate numbers from being generated, I added a button that, when clicked by a user, displays a message indicating that the value is being saved to avoid duplicates. However, when attempting to handle this on the server side controller, I enco ...

Transform jQuery code to its equivalent in vanilla JavaScript

While I am proficient in using jQuery, my knowledge of pure JavaScript is somewhat limited. Below is the jQuery code that I have been working with: $(document).ready(function() { $.get('http://jsonip.com/', function(r){ var ip_addre ...

Load a script in a specific div using React

Can anyone assist me with loading a script onto a specific component in my React application? Here is the script that needs to be loaded at the bottom-most div within my component: <div id="rexxxx"></div> <script> new carouselI ...

The perplexity caused by unescaped HTML and line breaks

I have created a platform similar to a forum, where users can input various strings such as: <<<<< >.< and so on. It is essential for me to maintain the formatting of new lines. Additionally, I need to condense multiple new lines in ...

Exploring the characteristics of $scope elements generated by the $resource factory service within AngularJS

I need to access attributes of an object that originates from a $resource factory service (REST API). services.js: myApp.factory('userService', ['$resource', 'backendUrl', function($resource, backendUrl) { return $resource ...

Upon refreshing the datatable, I encountered a issue where the checkbox cannot be selected

After updating my data table with new content through an AJAX request, I am facing an issue where I am unable to select the check-boxes in the table. I use a class selector to choose the rows that contain multiple check-boxes. The select event is placed in ...

Discover the index of the row when the value in the dropdown list is updated

I'm faced with a challenge regarding an HTML Table that contains a dropdown list in every row. I would like the background of each row to change whenever the value in the dropdown list is modified. Below is the code snippet: <table id="table1"> ...

The Node.js application is unable to locate the source file path

Currently, I am in the process of creating a simple quiz application. While working on this project, I encountered an issue with linking a JS file in an HTML template. Even though I have confirmed that the path is correct, every time I run my node app, the ...

Encountering issues with Office.context.document.getFileAsync function

I am experiencing a strange issue where, on the third attempt to extract a word document as a compressed file for processing in my MS Word Task Pane MVC app, it crashes. Here is the snippet of code: Office.context.document.getFileAsync(Office.FileType.Co ...

analyzing strings by comparing their characters to another string

In a scenario where I have two strings; let's call them string a="a-b-c" and string b="a-b". I am looking to determine whether every letter in string b is present within string a. ...

Simply output the integer value

Recently, I've been working on a function that I'm trying to condense into a one-liner code for a challenge on Codewars. You can find the problem here. Here's the code snippet that I currently have: export class G964 { public static dig ...

Top method for combining several external JavaScript libraries into a single one using webpack

Recently, I was diving into the world of webpack tutorial and it struck me that in order to combine everything into one module, scripts need to use require('./xyz'). Until now, I've always written individual scripts and loaded them in HTML u ...

Losing authentication token when refreshing with Nuxt asyncData and Axios

While testing a get API that retrieves an array of mail data through Postman, everything seems to be working smoothly. However, when I implement the asyncData method to fetch the array in my code, it only works once. Upon page refresh, I encounter a 401 er ...

Include image hover text without using HTML

I am looking to add a hover effect to some images using CSS and JS since I cannot directly edit the HTML file. The goal is to have centered text pop out when hovering over certain images. I know the div class of the image but unfortunately, I cannot add te ...

Lunar - incorporate route parameter into DOM query_operation

Is there a way to take a route parameter and use it to trigger a click event on a DOM element? The issue is that onBeforeAction is called before the DOM is fully loaded. Any suggestions on how to solve this problem? JS onBeforeAction: function(){ var ...

Issue: ng-file-upload validation is not functioning correctly, resulting in the form always being considered valid

I'm looking to implement a file-upload feature for each item in an array. In order to achieve this, I am utilizing the ng-repeat directive to cycle through the array and incorporating the ng-file-upload plugin to manage the file upload process along w ...