ng-transclude replaces the current content instead of appending to it

I've been diving into AngularJS lately and came across an interesting video that discusses using ng-transclude in a directive template to incorporate existing DOM elements.

Check out the code snippet below:

<html ng-app="myApp">
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width">
    </head>
    <body ng-controller="AppCtrl">
    <panel>
        <button>Click Me</button>
    </panel>

    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular.min.js"></script>
    <script>
            var app = angular.module('myApp', []);
            app.controller('AppCtrl', function() {

            });
            app.directive('panel', function() {        //can return a function (link) or an object
                return {
                    restrict: 'E',
                    transclude: true,
                    template: '<span> This is my custom span</span><div class="panel" ng-transclude>this is my div</div><span>Another span follows</span>'
                }
            });
    </script>
</body>
</html>

You can also view the problem on this fiddle.

Answer №1

This is the expected behavior of the most recent version.

Refer to Angular API on ng-transclude for more information.

"Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted."

If you test your code with Angular version 1.0.8, it will function as shown in the demonstration.

Answer №2

Here is an example of using a <span> as the transclusion host:

// Set up the template configuration and assign it to the tpl variable
var tpl = [
        '<span> This is a customized span element</span>',
        '<div class="panel">',
            '<span ng-transclude></span>',
            ' This is my div',
        '</div>',
        '<span ng-switch-when="divider"></span>',
        '<span>Another span comes after this one</span>'', // End
    ].join('\n');

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

Problem Encountered with Bootstrap 3 Date and Time Selector

I am currently utilizing the date/time picker created by Eonasdan, which can be accessed here. Below is the HTML code snippet from the example: <div class="container"> <div class="col-md-10"> <div class='well'> ...

Enhance your website with a dynamic header effect that smoothly transitions on scroll, utilizing the

When my page loads, I have a header that is positioned absolutely. I want to make it fixed at a certain point when scrolling, which works fine. The issue arises when trying to add an effect to the header (such as displaying with a delay from the top) whil ...

Why is my JSON object showing up as undefined in my Node.js POST request?

I have a CentOS server that is currently running a node.js HTTP server (code provided below). My goal is to pass JSON data from the command line by using the following CURL command: curl -X POST -H "application/json" -d '{"val1":"hello","val2":"my"," ...

Having trouble getting ng-bind-html-unsafe to work within an AngularJS directive?

I am encountering a specific issue with my code. In the jsFiddle I shared, I am attempting to utilize ng-bind-html-unsafe within a template in my directive. The value of the attribute that I'm passing (item{{itemColumn.field}}) is dependent on being i ...

The TypeScript Promise error codes TS2304 and TS2529 are causing confusion among

I came across the code below: function asyncTask(): Promise<string> { return new Promise<string>(resolve => resolve); } This code resulted in the following error: TS2304: cannot find name 'Promise' To address this issue, ...

Issue with toggling functionality on Material UI check boxes when they are printed in a loop

I am attempting to display checkboxes in rows of 4 dynamically, where the number of rows and checkbox values can vary. Below is my JSX code: matrix.map((row, index) => ( <TableRow key={index}> <TableCell al ...

Is there a way to set the <hr /> tag to display vertically?

Is there a way to make the <hr /> tag go in a vertical direction rather than appearing horizontally as it normally does? I am looking for a solution that can be used on a mobile site with broader compatibility across browsers, rather than relying on ...

Flipping through words to create dynamic text transformation

Is there a way to use Javascript to dynamically change the text in an H1 tag every 2 seconds without altering the HTML structure? For example: 1) Made for agencies... 2) Made for start-ups... 3) Made for small businesses... I want the words after "Made ...

Vuex: Clearing all data from the store and setting it back to an empty array

My Vuex store has a state variable called scannedList, which is initially set to an empty array []: state: { scannedList: [] } I have a mutation that adds ids to this array. I attempted to clear the entire state by using: store.commit('addToScann ...

YouTube's embedded video player is invincible and cannot be destroyed

Having trouble destroying an embedded YouTube video on the Plyr player. The player.destroy() method is being called without any errors, but it doesn't actually destroy the player. This issue is causing the previous video to load instead of a new one ...

Getting the length of a field in Internet Explorer without including the placeholder text

Is there a way to distinguish between the length of a placeholder and the length of content in a field using JavaScript when working with IE? I am facing an issue where Internet Explorer counts placeholder text as content, affecting the length calculatio ...

Exploring ReactJS Design Patterns: Comparing Class Components to Custom Components

As I delve into best practices and design patterns using React, I find myself pondering the choice between two similar solutions: The first solution involves a class that does not extend a component. Its constructor returns an element set based on an obje ...

The collapsed button on the Bootstrap 4 accordion flickers slightly as it expands, not reaching its full expansion

I'm currently working on implementing an accordion feature. I found inspiration from this component here on fiddle which utilizes bootstrap 4. While attempting to troubleshoot a bug in the SO forum, I noticed that on my page, the component seems to "b ...

What is the method for launching a new tab within an incognito window that is already open?

In the process of developing a Chrome extension, I am focusing on the functionality of creating a new tab from context menus within an incognito window. My current approach involves using the following script: chrome.windows.create({url: "https://google.c ...

What could be the reason for the undefined value of my variable

I am facing an issue with a function that I have written function collectData() { var data = []; data[0] = {name: "Sophia", age: 25, gender: "female"}; data[1] = {name: "John", age:30, gender ...

What steps can I take to decrease the padding of this footer?

Is there a way to reduce the height of the footer so it doesn't dominate the screen on both large and small devices? https://i.sstatic.net/nIQz6.png import { Container, Box, Grid } from "@material-ui/core"; const Footer = (props) => { ...

Tips for decreasing the dimensions of FontAwesome version 5.3.1

Implementing SVG using JavaScript is significantly larger, about 20 times, compared to Utilizing Web Fonts with CSS. This poses a major issue for me if I choose to go with Using SVG via JavaScript, without even factoring in other javascript libraries such ...

Animate hovering over a specific element within a group of similar elements using jQuery

Hi there! I recently started exploring Js and jQuery, and I was able to create a cool width change animation on a div when hovering over another. However, I ran into an issue when trying to implement this with multiple sets of similar divs. Whenever I hove ...

Using Jquery to make a single ajax request and store the JSON response for future use

My code includes the following: var response = ""; function send_ajax(){ if(response == ""){ $.ajax({ url: url type: 'POST', dataType: "JSON", success: function(data){ response = data; } }); } } The issu ...

Combining Select Options with AngularJS

I am completely new to AngularJS framework and just experimenting with it. Therefore, I'm not entirely sure if my current approach is the best or right way to achieve my goal. My aim is to create a 3-level chained ajax-filled select boxes, and while ...