Can transclusion be achieved while maintaining the directive's scope in Angular?

Can we achieve the following functionality in Angular?

<div ng-controller="MainCtrl" ng-init="name='World'">
    <test name="Matei">Hello {{name}}!</test> // I expect "Hello Matei"
    <test name="David">Hello {{name}}!</test> // I expect "Hello David"
</div>

Although my directive is simple, it seems to be not working as expected:

app.directive('test', function() {
  return {
    restrict: 'E',
    scope: {
      name: '@'
    },
    replace: true,
    transclude: true,
    template: '<div class="test" ng-transclude></div>'
  };
});

I attempted to use the transclude function to modify the scope and it did work. However, the issue lies with losing the template.

app.directive('test', function() {
  return {
    restrict: 'E',
    scope: {
      name: '@'
    },
    transclude: true,
    template: '<div class="test" ng-transclude></div>',
    link: function(scope, element, attrs, ctrl, transclude) {
      transclude(scope, function(clone) {
        element.replaceWith(clone);
      });
    }
  };
});

Is there a way to achieve this desired functionality while retaining the template intact and appending the clone into the element with the ng-transclude attribute?

You can test your solution using this Plnkr link: http://plnkr.co/edit/IWd7bnhzpLmlBpoaoJct?p=preview

Answer №1

It seems like your aggressive manipulation of the element led to that outcome.

Instead of using replaceWith, there are other methods you can utilize to interact with the current element.

You have the option to append it at the end, prepend it, or select a specific template element and place it inside... any DOM manipulation is possible. For example:

app.directive('test', function() {
  return {
    restrict: 'E',
    scope: {
      name: '@'
    },
    transclude: true,
    template: '<div class="test">This is test</div>',
    link: function(scope, element, attrs, ctrl, transclude) {
      transclude(scope, function(clone) {
        element.append(clone);
      });
    }
  };
});

In this case, I chose to position it after the element, resulting in:

This is test
Hello Matei!
This is test
Hello David!

Note that I excluded ng-transclude from the template as manual handling suffices.

In short: Experiment with the element, avoid mere replacements, and strategically insert transcluded content where desired by selecting the appropriate element and method.

For further demonstration, here's an additional example: http://plnkr.co/edit/o2gkfxEUbxyD7QAOELT8?p=preview

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

Populate an HTML layout with MySQL information and dynamically add the content to the page using JavaScript

I'm facing a challenge with creating an about us page for a website. I am using a template to structure the page and I want to populate it with MySQL data. I have enclosed the entire <div> of the personcard within a <script> tag, but the p ...

Updating state in React is not possible

I am having trouble updating my state (specifically with setCoords). The API request is returning a 200 status code and the elements I need are present: https://i.stack.imgur.com/a8QzN.png Below is the code I am working with: const App = () => { co ...

I am encountering difficulty in printing multiple documents from FireStore

I am facing an issue where I can successfully retrieve and print all documents from a Firestore collection one by one using console.log(). However, when attempting to display these documents on the screen, only the most recent document is showing up. Here ...

Preserve the Redux state when transitioning from a popup to the main window

My authentication process involves using auth0 to authenticate users. After selecting a provider, a popup opens for the user to choose an account to sign in with. With the help of the Auth0 sdk, I am able to retrieve user information such as email and nam ...

The scope remains static and does not update

I'm encountering an issue with an http.get request. Index.html <div ng-repeat="element in elements"> <p>{{element.elementText}}</p> </div> app.js In my app.js file, I have two controllers. The first one initializes the $sco ...

jQuery problem causes page to scroll when button is clicked

Is there a way to smoothly scroll to the second section of the page when a button is clicked using jQuery? $('.home_scroll_btn a').on('click', function(){ var scrollPosition = $('#intro-home').offset().top; $( ...

Issue with padding in Material UI button component not being applied as expected

I am struggling with applying padding and styles to my Material UI component. Take a look at the code snippet below: import "./css/Landing.css"; import { Button } from "@mui/material"; function Landing() { return ( <div class ...

Integrate functionality to track elapsed hours in stopwatch timer

Struggling to incorporate hours into my JS Stopwatch timer, the math for calculating the hours section is proving difficult. This is what I have so far, but I suspect the issue lies within the h variable. function formatTime(time) { var h = m = s = ...

What is the best way to transmit the server response information from a fetch API to the client?

After receiving a response with the expected results from an API call using fetch API and a json object, I am looking for ways to send these results to the client in order to display them on the interface. The server-side operation was conducted through th ...

What is the best way to add data to my collection using the main.js file on the server side in a Meteor application

I am a beginner with Meteor and trying to customize the tutorial codes. I have a code that listens for packets on my server-side main.js. Now, I need to store the data printed on the console into my database collection. import { Meteor } from 'meteor/ ...

Adjust the stroke and fill colors of an SVG element when hovering over it

I am facing a challenge with an SVG image that I have: https://i.stack.imgur.com/r4XaX.png When hovered over or clicked, it should change to https://i.stack.imgur.com/EHRG2.png Current Icon <svg width="24" height="24" viewBox="0 0 24 24" fill="non ...

Sort data by checking either multiple or single checkbox options in AngularJS; if none are selected, display all results

My goal is to implement a filter in my AngularJS code that will filter data based on selected checkboxes. If no checkbox is selected, all results should be displayed without any filtering. Currently, the issue I am facing is that the data is only displayed ...

Troubleshooting problems with scrolling on JavaScript in Edge, Opera, and Chrome

Currently, I am developing a fun CSGO-inspired box opening feature on my food recipe website that randomly selects recipes for users. However, I have encountered some challenges with the scrolling functionality. It seems to be incompatible with certain bro ...

Tips for extracting both the div and entire inner content using JavaScript

I need to retrieve the inner content of a div using JavaScript For example: <div id="content" style="height: 20px; overflow: hidden"> content<br>content<br>content<br> </div> This is my HTML code. I only know the div&apos ...

Enhance your cloud functions by updating data

Recently, I encountered an issue with a function I wrote that interacts with the Real Time Database. Every time I attempted to write data to a specific node, it would add the complete dataset and then promptly delete everything except one entry. https://i ...

ASP.NET service with an added quotation mark in the JSON response!

I am trying to make a web service method call in JavaScript within an ASP.NET 3.5 environment. After inspecting the result using Firebug, I found the following: {"d":"[{\"TI\":\"www\"},{\"TI\":\"www1\"}]"} It seem ...

Adding a QR code on top of an image in a PDF using TypeScript

Incorporating TypeScript and PdfMakeWrapper library, I am creating PDFs on a website integrated with svg images and QR codes. Below is a snippet of the code in question: async generatePDF(ID_PRODUCT: string) { PdfMakeWrapper.setFonts(pdfFonts); ...

Experiencing an anonymous condition post onChange event in a file input of type file - ReactJS

When using the input type file to upload images to strapi.io, I noticed that an unnamed state is being generated in the React dev tools. Can someone explain how this happened and how to assign a name to that state? https://i.sstatic.net/ZyYMM.png state c ...

If there is a lack of text at the beginning, then insert the

I am currently trying to figure out a solution to automatically add our domain name if it is not included when entering the username. In the code snippet below for my form, I want the script to check if "domainname\" is present before the username. I ...

Rows per page options fail to display in the DataTable component

I need to display a dropdown selector for rows per page in the DataTable component from PrimeVUE. This is the sample HTML code I currently have for the DataTable: <DataTable :value="comunicaciones" :paginator="true" :rows="numFilas" :rowsPerPageOption ...