The nested transclude directive is displaying the inner transcluded content in the incorrect location

I created a directive called myList that transcludes its content. The issue arises when I try to nest a <my-list> element inside another <my-list>.

Check out the JS Fiddle here: http://jsfiddle.net/fqj5svhn/

The directive is implemented as follows:

var MyListDirective = (function () {
    function MyListDirective() {
        this.restrict = 'E';
        this.replace = true;
        this.transclude = true;
        this.scope = {
            myListType: '='
        };
        this.controller = function () {
            this.classes = 'my-class';
        };
        this.controllerAs = 'myList';
        this.bindToController = true;
        this.template = '<ul ng-class="myList.classes" ng-transclude></ul>';
    }
    return MyListDirective;
})();
angular.module('myApp', []).directive('myList', function () {
    return new MyListDirective();
});

An example of how to use the directive:

<div ng-app="myApp">
    <my-list my-list-type="'someType'">
        <li>foo</li>
        <li>bar</li>
        <li>
            <my-list my-list-type="'anotherType'">
                <li>cats</li>
                <li>dogs</li>
            </my-list>
        </li>
    </my-list>
</div>

The output you might expect:

<div ng-app="myApp" class="ng-scope">
    <ul ng-class="myList.classes" ng-transclude="" my-list-type="'someType'" class="ng-isolate-scope my-class">
        <li class="ng-scope">foo</li>
        <li class="ng-scope">bar</li>
        <li class="ng-scope">
            <ul ng-class="myList.classes" ng-transclude="" my-list-type="'anotherType'" class="ng-isolate-scope my-class">
            </ul>
        </li>
        <li class="ng-scope">cats</li>
        <li class="ng-scope">dogs</li>
    </ul>
</div>

Currently, it seems like the list items from the inner myList are being included in the transclusion of the outer myList. What I desire to happen:

<div ng-app="myApp" class="ng-scope">
    <ul ng-class="myList.classes" ng-transclude="" my-list-type="'someType'" class="ng-isolate-scope my-class">
        <li class="ng-scope">foo</li>
        <li class="ng-scope">bar</li>
        <li class="ng-scope">
            <ul ng-class="myList.classes" ng-transclude="" my-list-type="'anotherType'" class="ng-isolate-scope my-class">
                <li class="ng-scope">cats</li>
                <li class="ng-scope">dogs</li>
            </ul>
        </li>
    </ul>
</div>

Any suggestions on how to achieve this?

Answer №1

The issue arises because the browser expects the <li> element to be nested inside a <ul>, but in your case it is within a <my-list> which is not valid markup. This misalignment occurs before Angular initializes and runs directives, leading to unpredictable behavior in how the browser interprets the faulty markup - in this scenario, causing the <li> elements to appear disjointed.

To illustrate this problem, I have created a replacement in this example, using <div> instead of <ul> and <li>. Since <div> does not require specific nesting rules, transclusion functions correctly without issues.

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

Managing the lifecycle of a background worker in JavaScript (Node.js) - start and stop operations

I have a JavaScript function in my code that I refer to as a 'worker' which checks if it is running and performs some tasks class Application { async runWorker() { while (true) { while (!this.isStarted) ...

Is there a way to replace the standard Apache login/password popup box with a customized one using a combination of JavaScript, HTML

Is there a way to customize the default Apache login box with a custom design using JavaScript, HTML, and PHP? Thank you! ...

The ffmpeg Image2pipe command keeps getting stuck indefinitely when attempting to capture an image stream from PhantomJS

Allow me to illustrate the issue I am encountering through my code... Below is my JavaScript file tailored for use with PhantomJS. It instructs the page to open and capture screenshots, storing them in stdout. var page = require("webpage").create(); page ...

"Utilizing the power of MVC Modelbinding with the seamless integration

I am currently facing an issue with my Modelbinding and struggling to understand why it is not working. Here is the Controller snippet: public class ItemListController : Microsoft.AspNetCore.Mvc.Controller { [HttpPost] public async Task<IA ...

Implement a unique navigation bar for each page using layout.js in Next.js

https://i.stack.imgur.com/Ha3yC.pngI have a unique setup in my next js project with two different navbar layouts and ten pages. I'm looking to assign navbar one to five pages and navbar two to the remaining pages using layout.js. Can anyone provide gu ...

Tips for incorporating a JavaScript script into local HTML code

I am facing an issue with my code on jsfiddle. It works perfectly there, but when I try to run it locally, it doesn't seem to work. I have checked the code multiple times and even downloaded the jQuery file to link it, but still no luck. I feel like i ...

What steps can I take to resolve this error when utilizing an npm package in client-side JavaScript?

Just when I thought I was getting the hang of socket.io, I hit a roadblock on the client side. Following my instructor's advice, I installed socket.io-client package for my project. But when I tried to use it in my client-side JS code, I encountered a ...

Display the Astro component based on the query of the current page's type

I am using Astro, GraphQL (Apollo Client), Typescript and React. Within my dynamic route: [...slug].astro file, I have a requirement to conditionally display a specific Astro component. I was able to achieve this using the following logic: {data.page.ty ...

Deselect a checkbox that is already selected and choose the current option in the multiselect dropdown

I've created a code that allows for single select in a multiselect dropdown, disabling other options once one is chosen. However, I don't want to disable the checkboxes and would like to uncheck the selected option if a new one is chosen, all whi ...

I'm wondering if there is a method to access this JSON feed solely through a browser client

Looking to develop a custom client for last.fm? Find your music "station" feed in JSON format here: . However, encountering an issue when trying to access it using $.getJSON(): The 'Access-Control-Allow-Origin' header is not present on the re ...

What's the deal with receiving [object Object] in my JavaScript JSON document?

When I use console.log(values), it returns "[object Object]" instead of logging the array as expected. This is the code snippet I'm working with: let values = { "coins": 0, "griffinFeathers": 0, "souvenir": 0, "cogs": 0, "cats": 0 ...

Error encountered in Express.js blogging app: Issue arises when attempting to filter posts by category, resulting in a "Cast to ObjectId failed" error

Currently, I am developing a blogging application using technologies like Express, EJS, and MongoDB. In the application, I have structured posts into different categories, each stored in its own collection. However, I encountered an issue while attemptin ...

Implementing a keypress function that can handle duplicate names

HTML <input name="pm" type="text" value="0"/> <input name="pm" type="text" value="0"/> <input name="pm" type="text" value="0"/> <input name="total" type="text" value="0" disabled="disabled"/> Javascript $('[name="pm"]' ...

Illuminate the current page

I have been working on a website with around 20 pages that all have a side navigation bar. To make it easier to manage, I decided to centralize the links in a JavaScript (JS) file and include it on each HTML page. This way, any changes can be made quickly ...

Designing a final splash screen for my game with the help of JavaScript, Cascading Style Sheets, and

I'm facing a challenge with setting up an end screen for my candy crush game. I have implemented a timer, but when the time runs out and certain conditions are met, the end screen fails to appear. Do you know what might be causing this issue? functio ...

Can someone help me figure out the issue with my Angularjs ng-repeat implementation?

After spending hours trying to figure out why something so simple is not working, I'm at a loss. Testing with a dummy list proves the functionality works, but when I connect my server-side data source, it fails. The JSON returned from the AJAX call i ...

The implementation of a generic function interface in Typescript can pose a challenge

I've been working on incorporating a generic function interface, but I'm facing some challenges in getting it to function properly. IToken.ts export interface IToken { token: string; expires: number; } ITokenMapper.ts export interface ...

Ways to organize the information within the Ul and Li elements

I need help sorting the data within <ul> and <li> elements using jQuery. Below is a snippet of my code: <ul id="rootUl"> <li> <div id='title'>MSFT</div> <div id='price'>230</d ...

javascript ajax is not executing correctly

With the help of Ajax, I have developed a console that allows me to dynamically execute PHP functions. This is how it appears https://i.sstatic.net/Wj2Ww.png The issue arises when the console gets filled with numerous commands, making it difficult to rea ...

Apply a specific class to a list once scrolling beyond a certain offset of a group of division elements

I seem to be getting close, but I'm struggling to finalize this task. Essentially, as you scroll down to each image, the div containing that image's offset from the top of the window (with a buffer of -500) should add a .selected class to the cor ...