Angular directive loading twice because of nested directive in Javascript and $compile issue

I am encountering an issue with directives nested within directives. In order to meet the requirements of our designers, I need the contents to be direct children of the DOM node.

  <div>
    <my-directive style="color: blue;">

      <p>Name: {{ ctl_a.fname }} {{ ctl_a.sname }}</p>
      <p>External Test: {{ xternal }}</p>

      <div>
        <nested-directive incoming="ctl_a.a_counter"></nested-directive>
      </div>

    </my-directive>
  </div>

What are the most effective methods for ensuring that this loads correctly? For example, allowing "my-directive" to access ctl_a.fname and enabling "nested-directive" to access $scope.incoming as passed in by "ctl_a.a_counter".

I have provided a plunk demonstrating the issues I am facing when using $compile. When utilizing $compile, the nested directives execute twice - once during the outer directive compile method, and then again manually. Interestingly, only the manual execution seems to render the contents correctly.

If I utilize ng-transclude, none of the attributes passed to the inner directive function properly without prefixing with $$prevSibling or $parent because ng-transclude generates a new scope. This necessity to reference it in this manner feels inherently flawed.

Edit: Another plunk is available here, branching off from the initial one. In this version, I illustrate the usage of ng-transclude and how $parent must be utilized to access the controller for its directive.

Thank you.

Answer №1

It appears that there may be more information for you to consider. One important step is to include terminal: true in your directive definition object. This will prevent Angular from processing the HTML within the my-directive tags until you manually compile it. Below is an updated snippet of code based on your plunker:

function myDirective($compile) {
  var directive = {
        compile: compile,
        controller: controller,
        controllerAs: 'ctl_a',
        replace: true,
        terminal:true, //<=======
        restrict: 'E',
        scope: {
            data: '='
        }
    };

    return directive;

Answer №2

It appears that the data property of my-directive is not being utilized. You can safely eliminate the following code from my-directive:

    scope:{
        data: '='
     }

Furthermore, there is no longer a need for manual compilation as shown below. Therefore, you can remove this line as well.

$compile(element.contents())(scope);

Check out this working example on Plunker

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

PHP and JavaScript Form: Include the page URL in the email form when submitting

After submitting a basic form, I am struggling to include the URL of the page in the email notification to track where the user completed the form. I have attempted various solutions from this forum, but unfortunately none of them seem to work. How can I ...

Identifying Shared Links in Node.js

Is there a way to determine if a file-system path is a hard link using Node.js? The fs.lstat function provides a stats object that can identify if a path is a hard link by returning true for stats.isDirectory() and stats.isFile() respectively. However, the ...

Guide to designing a bar graph using HTML5 for a web app optimized for iPad

I am in the process of converting my iOS native app for iPad to a web app using HTML5. However, I am encountering an issue with creating a bar graph for the HTML5 app. Is there any documentation or built-in API available for this specific task? On iOS, we ...

Finding the nearest ancestor with a specific class using JavaScript

Is it possible to find the closest ancestor by class using a partial class name? For example: <div class="parent-1"> <div class="child"></div> </div> I'd like to achieve something like this: document.get ...

Utilize jQuery to Transform DateTime URL Parameter

I am currently facing an issue on my web page where I need to convert a UTC date and time parameter into a datetime value using jQuery. Here is an example of the parameter passed: Example: https://test.com/SentValues.html?dtype=9/23/2015+2:15:16+PM&l ...

1. Common obstacles in the functionality of data binding2. Constraints

Working on a basic controller to perform some calculations, which is a simplified version of a more complex project. The issue I'm facing is that the result displayed in the HTML gets recalculated every time there's a change, but when calculating ...

Transforming Attribute Directives into Elements in Angular 2

I've been trying to wrap my head around this Attribute Directive feature in Angular 2. Initially, I thought that directives could only be created using Attributes, but after some experimentation, I realized that I can also create directives using Ele ...

Is it possible to implement nested views with Angular's built-in ngRoute module (specifically angular-route.js v1.3.15)?

For a project I'm working on, we have decided not to use UI router and are only using ngRoute. I need to create nested views - is it possible to achieve this with just ngRoute without any additional library support? If so, could you please provide a w ...

Can you explain the purpose of the array as the second parameter in an Angular directive?

I need to understand a specific customer directive so I can implement it into our AngularJS application. The second parameter seems to be a part of a string and then the main function: mainApp.directive('uiCalendar', ['uiCalendarConfig&apo ...

Combining values with identical keys in a PHP MySQL D3 data set

Is there a way to convert data from a MySQL database into a D3 line chart? I have the following data: [{"key":"Branch1","values":["21","1961"]},{"key":"Branch2","values":["21","1961"]},{"key":"Branch2","values":["22","20040"]}] And I want to transform i ...

Angular retrieving a document collection from Firebase based on a specific field

I am trying to retrieve collection data based on the UserId field. retrieveData(){ const data$ = this.firestore.collection(this.trackerCollection,ref=> ref.where('UserId','==',"WrKDk0XSNjU20FI0EVRvADzvNHz1")).snapshotCha ...

Ways to determine the success of $wpdb->query and retrieve the outcome

Currently, I am in the process of developing a WordPress website, I have implemented a form that allows users to make modifications and update the database: Below is the HTML/PHP code snippet: echo '<form class="form-verifdoc" target=&q ...

Troubleshooting: Issue with Angular 2 bidirectional data binding on two input fields

Hi there, I am encountering an issue with the following code snippet: <input type="radio" value="{{commencementDate.value}}" id="bankCommencementDateSelect" formControlName="bankCommencementDate"> <input #commencementDate id="bankCommencementDat ...

Personalizing Bar Charts with ng-google-chart for a Unique Look

I have successfully implemented Angular google chart (ng-google-chart) to draw a Bar graph using the example provided at . However, I am facing an issue where I want to dynamically assign colors to the bars based on their values. Unfortunately, I haven&ap ...

Continuous addition of Node structures in a tree

I am attempting to append a node tree to the DOM that has been created using createHTMLDocument. Originally, I approached it like this: (doc represents the node tree) while(doc.head.children.length > 0){ iframewin.document.head.appendChild(doc. ...

Tips on sending checkbox data as an array to a PHP script using jQuery and AJAX

I am working with a set of checkboxes like so: <input type='checkbox' name='name[]' value='1' /> <input type='checkbox' name='name[]' value='2' /> <input type='checkbox' ...

Implementing closure within a recursive function allows for better control

One of my functions is designed to take a parameter and print the last number in the Fibonacci Series. For example, if the parameter is 3, it would return 2 as the series progresses like 1, 1, 2. function recursionFib(num){ if(num ...

Tips for incorporating real-time data into your nodeJS and express applications

I am currently utilizing express for managing all the routing in my web application. Additionally, I have integrated firebase to store my data. For organization purposes, I decided to divide my code as follows: index.js: This file serves as the main node ...

What happens to the npm package if I transfer ownership of a github repository to a different user?

I was considering transferring a GitHub repository to another user or organization, but I have concerns about what will happen to older versions of the npm package associated with it. Let's say my Node.js package is named node-awesome-package. Versi ...

Understanding Mongodb: the process of populating a schema that is referenced within another schema using an API

Looking to make adjustments to my Api in order to populate a referenced schema. Here's the schema I am working with: export const taskSchema = new Schema ({ user:{ type: String, required: true }, project: { type ...