Unusual occurrences with nested Angular directives

I have been trying to implement directives within other directives, but the results are not what I expected. Can anyone help me understand this code snippet:

var app = angular.module('blah', []);

app.directive('one', function() {
    return {
        restrict: 'E',
        replace: true,
        template: '<outer>one</outer>'
    };
});

app.directive('two', function() {
    return {
        restrict: 'E',
        replace: true,
        template: '<outer>two</outer>'
    };
});

app.directive('outer', function() {
    return {
        restrict: 'E',
        replace: true,
        transclude: true,
        template: '<div ng-transclude></div>'
    };
});

HTML:

<outer>whatever</outer>
    <one></one>
    <two></two>
    <outer>something</outer>

The resulting DOM is:

<div ng-transclude=""></div>
    <outer></outer>
    <two></two>
    <outer>something</outer> 

JSFiddle: http://jsfiddle.net/WPpUL/

Is there an issue with the code?

EDIT:

Expected output DOM:

<div ng-transclude>whatever</div>
    <div ng-transclude>one</div>
    <div ng-transclude>two</div>
    <div ng-transclude>something</div>

Answer №1

If we avoid using the replace method, we can manually handle the process to keep angular content and achieve the desired outcome.

1) Adjust replace: false instead of true in One and Two components to satisfy angular requirements.

2) Manually update the HTML by implementing this link function for One and Two:

link: function(scope, element, attrs) {
    element.replaceWith(element.html());
}

This will produce the following result:

<div ng-transclude=""><b class="ng-scope">whatever</b></div>
<div ng-transclude=""><b class="ng-scope">one</b></div>
<div ng-transclude=""><b class="ng-scope">two</b></div>
<div ng-transclude=""><b class="ng-scope">something</b></div> 

The B tags were added around text nodes to eliminate automatically generated SPANs.

You can view the updated fiddle here: http://jsfiddle.net/WPpUL/7/

Answer №2

To resolve this issue, make sure to enclose the template within a root element.

template: '<div><outer>one</outer></div>'
template: '<div><outer>two</outer></div>'

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

Concerns with the window's onload function

window.onload = prepareButton; function prepareButton() { document.getElementById('slist').onclick = function() { window.location = "students"; } } Whenever I click on a slist element, which is actually a <p> tag formatt ...

Asynchronous NestJs HTTP service request

Is there a way to implement Async/Await on the HttpService in NestJs? The code snippet below does not seem to be functioning as expected: async create(data) { return await this.httpService.post(url, data); } ...

Passing the value selected from a datepicker to PHP without refreshing the page through the use of XMLHttpRequest: Guide

Is it possible to transfer the datepicker value to PHP without reloading the HTML page by using XMLHttpRequest()? The intention is to utilize this date value for a subsequent query and present it on the same HTML page. <input type="date" id="month" o ...

Exploring and accessing the properties of objects in JavaScript

While attempting to access the email and password fields, an unexpected '0' seems to have appeared. The object retrieved from RethinkDB appears fine without this '0'. However, when using Lodash's _.assign() method like so: var use ...

Retrieve information from api and showcase it in html

Recently, I came across an interesting API file that caught my attention: My goal is to extract information from this API and present it on a HTML page in a visually appealing format. Despite scouring various forums, I have yet to find a solution that fi ...

What is the best way to eliminate concealed divs from the view source of a webpage?

On my HTML page, I have some hidden DIVs that can still be viewed in the page source. I want to ensure that these DIVs are not visible to users when they inspect the page source. Is there a way to achieve this using Javascript or another solution? ...

What prevents me from utilizing interpolation within a directive?

I have come across a couple of articles discussing the topic of "Assigning a scoped variable to the value of an HTML attribute tag". Here are the references: https://docs.angularjs.org/guide/interpolation How to assign angularjs variable value to html el ...

Step-by-step guide to creating a pop-up div that appears on hover and remains visible when clicked

I'm trying to figure out how to make a popup appear when the mouse hovers over it and then stay visible when clicked on. The issue I'm facing is that currently, the popup disappears when the mouse moves away from it. How can I modify the code so ...

CSS3 Animation for Enrollment Progress Bar

https://i.sstatic.net/aYwHP.png How can I best incorporate this functionality? <div class="container"> <h2>Simple Progress Bar</h2> <div class="progress"> <div class="progress-bar" role="progressbar" aria-valuenow="70" ...

What is causing the loss of context for 'this' in the latest Angular 1.5 components?

Encountering a strange issue with the new components. Previously, in version 1.4 directive, we had this block of code... (function () { 'use strict'; angular.module('app.board').directive('dcCb', dcClipboardCopy); funct ...

issues with jquery functionality on user control page

For searching through dropdown lists in my project, I have implemented the Chosen jQuery plugin. In the Master page before the closing body tag, ensure to include the necessary CSS and jQuery script files. <link href="/assets/css/chosen.css" rel=" ...

Tips for populating two select tags with jQuery AJAX using a JSON document

Looking for help with my HTML code that includes two select tags. I want to use AJAX to populate the 'collegeselect' based on the selection in the 'departmentselect'. HTML CODE titled 'collegedepartment.html' <html> ...

Issue encountered: Unable to rename directories with contents on Windows 10 using fs.rename

I have come across several questions that relate to this issue, but none of the solutions seem to work for me. When using node.js, I am able to rename a directory only if it is empty. As soon as I add content to the directory, I receive the error message: ...

The Array.splice() method in Angular JS may result in undefined elements

Hey there! Currently, I am tackling the task of manipulating my Array by inserting objects at index 0 with the push method and eliminating items using splice. As per my understanding, when you splice an item from an array, it should not result in an &apos ...

I need to confirm the existence of two columns, "name" and "group", in my database. If they are found, I want to display a message saying they already exist. If they are not found

How can I modify this HTML with AJAX to display a successful message and insert into the database, but also show an error message if the name already exists after validation? <form action="" id="manage-project"> <label for=&qu ...

Issue found in React Js test - TypeError: source.on does not exist as a function

I'm encountering an issue with my post request using multipart/form-data. Everything runs smoothly, except for the tests which are failing. When running the tests, I encounter an error message: TypeError: source.on is not a function. This is the code ...

Styling a Pie or Doughnut Chart with CSS

I am working on creating a doughnut chart with rounded segments using Recharts, and I want it to end up looking similar to this: Although I have come close to achieving the desired result, I am encountering some issues: Firstly, the first segment is over ...

Continuously cycling without progressing to the subsequent directory

My goal is to create a library function that utilizes a JSON file generated by the directory tree tool to recursively iterate through each folder in order to construct an interactive <ul> list. During testing, I noticed that it gets stuck in an infin ...

Clicking on an anchor tag will open a div and change the background color

.nav_bar { background: #c30015; margin-left: 50px; float: left; } .nav_bar ul { padding: 0; margin: 0; display: flex; border-bottom: thin white solid; } .nav_bar ul li { list-style: none; } .nav_bar ul li a { ...