How can you render sub-directives using Transclude and ng-bind?

Lately, I've been struggling to figure out how to dynamically change the content of a directive in AngularJS.

Initially, in my HTML, there is a parent directive with a child directive inside. Every now and then, I need to update the content of the parent directive, but the child directive that I'm trying to insert isn't being initialized by AngularJS. To better illustrate my issue, I created a JSFiddle: http://jsfiddle.net/koj2e1th/2/

When I try to update the content using $timeout, the directive isn't properly initialized:

$timeout(function(){
    html = '<child-dir>TIMEOUT</child-dir>'
    scope.content = $sce.trustAsHtml(html)
}, 2500)

I attempted to use $compile (as suggested in other posts) but couldn't get it to work correctly. Can someone please explain how to make $compile function in this scenario and ensure that my child-dir gets rendered properly?

Thank you in advance!

Answer №1

To ensure the child-dir directive is compiled correctly, it must be compiled with a scope before being added to the DOM. Learn more

var example = angular.module('example', []);
example.directive('parentDir', function($sce, $timeout, $compile) {
    return {
        restrict: 'E',
            transclude: true,
            template: '<div ng-bind-html="content"></div>',
        link: function (scope, element, attrs, controller, transcludeFn) {
            transcludeFn(function(html) {
              $timeout(function() {
                html = _.reduce(html, function(carry, domElement) {
                  if (domElement.outerHTML) {
                      return carry + domElement.outerHTML
                  } else {
                    return carry;
                  }
                }, '')
                scope.content = $sce.trustAsHtml(html)
              })
            })
            var el = $compile( "<child-dir>TIMEOUT</child-dir>" )(scope );
            element.parent().append( el );
        }
    }});

example.directive('childDir', function($sce) {
    return {
        restrict: 'E',
            transclude: true,
            template: '<div>CHILD DIR</div>'
    }}); 

Answer №2

It appears from the provided code snippet that you are attempting to manage transclusion manually.

However, there is no need to do so with the availability of the tranclude property and ng-transclude attributes.

You can enhance your directive definitions to incorporate this functionality as shown below:

/* ... */
.directive('parentDir', function(){
   return {
     transclude: true,
     link: function(){ /* Any necessary DOM manipulation logic here */ },
     template: '<div ><h2>Parent Directive</h2><div ng-transcude></div></div>'
   };
})
.directive('childDir', function(){
   return {
     transclude: true,
     template: '<div ><h4>Child directive</h4><div ng-transclude></div></div>'
   };
});

Please note the utilization of the ng-transclude attribute in the template. This informs AngularJS regarding where exactly to place the transcluded elements/directives.

Thus, if your directives were structured like this:

<parent-dir>
   <child-dir></child-dir>
</parent-dir>

the content within <child-dir> would be inserted into the <div ng-transclude> section of the <parent-dir> template in the final rendered output.

View Demo

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

Leverage the power of mathematical functions within Angular to convert numbers into integers

In my Angular 7 Typescript class, I have the following setup: export class Paging { itemCount: number; pageCount: number; pageNumber: number; pageSize: number; constructor(pageNumber: number, pageSize: number, itemCount: number) { thi ...

Using JavaScript, insert a new date row onto a JSP page

When I click on a hyperlink, I want to add a new row to a jsp page. The functionality is working correctly, but the date function class="dateTxt" is not functioning in the new row. Below are the details of the javascript and jsp function. Javascript: fun ...

React's performance severely lags when traversing through JSON data

I have been working on fetching a JSON API using the fetch() method and displaying it in a Reactjs app. It worked perfectly fine with smaller JSON lists containing up to 100 items. However, when I attempted to do the same with a larger list containing 900 ...

The Android webview is blocking the display of a frame due to its X-Frame-Options being set to 'DENY'

Encountering an issue while attempting to display a Google calendar in a webview, an error is displayed: [INFO:CONSOLE(0)] "Refused to display 'https://accounts.google.com/ServiceLogin?service=cl&passive=1209600&continue=https://www.google.co ...

Instructions on adjusting column visibility after refreshing the page

Hey there, I'm struggling with setting up a cookie in JavaScript for the first time. I've been trying to load the cookie in my browser but haven't had much luck so far. Below you can find the HTML and jQuery code I have used: <html> &l ...

Locating the ID of the child div that was clicked within a parent div element

My HTML code snippet looks like: <div id="edit" ng-click="editFunction($event)"> <span id="1"> click1 </span> <span id="2"> click2 </span> <span id="3"> click3 </span> <span id="4"> ...

Is it possible to return a string and send it to a different HTML file using AJAX POST?

I am working on setting up an AJAX POST request from my Chrome Extension to my Node.js server. The goal is to receive a simple string response and then display it in an HTML file. Below is the code I have written so far: postrequest.js request("https:/ ...

Re-sequence a contiguous array by mapping and filtering its elements

Within my React code, I have a list component that utilizes array.map to display a list of items. The list items have alternating backgrounds; every other item's background color is determined by whether the id field from the data structure is even o ...

Troubleshooting a CSS problem with iPad browsers

I have a specific issue related to CSS on iPad. I am working with a set of sublinks and have defined the styles in CSS as follows: #leftNav .searchBySub {...} #leftNav a.searchBySub:hover {...} #leftNav .searchBySubClicked {...} In my JavaScr ...

Use a filter to narrow down results based on a column containing comma-separated values, as well as another specified

I am encountering an issue when attempting to apply filters on multiple columns within an object. The filters need to be applied based on the selection made in two drop-downs: one is directly linked to the ID, while the other holds the name but needs to be ...

Changing the text displayed after a checkbox is checked

I am currently working on creating a form that includes both checkboxes and text entry fields. The goal is to have related text appear next to each checkbox when it is checked. However, my current code does not seem to be functioning as expected: HTML: & ...

Changing a numeric string into a number within an Angular 2 application

Looking for advice on comparing Angular 2 expressions. I have an array of data stored as numeric strings in my database and I need to convert them to numbers before applying a condition with ngClass for styling purposes. Any suggestions on how to perform ...

Can Vuejs delay the calculation of a computed property until the component is "ready"?

Within my Vue.js application, I have a `computed` property that relies on a value fetched from an AJAX call. I am looking for a way to delay the calculation of this `computed` property until after the `ready` method has completed. While everything is fun ...

Resposiveness of force-directed graph is lost

const container = document.getElementById("container"); const svgElement = d3.select(container).append("svg") // Get the width and height computed by CSS. let width = container.clientWidth; let height = container.clientHeight; const colorScale = d3.scale ...

How to handle the Conflict in jest snapshot testing when the source is deleted and target is modified?

While working with Bitbucket, I encountered an error when trying to merge from the develop branch to master: The file is currently in a conflicted state and needs to be resolved manually before the pull request can be merged. If I change the conflicting ...

Tips for fixing flickering tables and bringing the scrollbar back to the top in your DataTable Forge viewer

Presently, I am working with a DataTable that consists of 100 rows and is being set up using lists. The lists dynamically change based on the selected name from a drop down. To achieve this, I use: $("#datatable").remove(); this.datatable = new Au ...

What is the best way to attach a Child mesh to a Parent mesh?

I am facing an issue with loading a facial mesh and separate eye mesh into three.js from Blender. The face is set as the parent and eyes as the child in Blender. How can I accomplish this task successfully? Additionally, there seems to be a problem with l ...

Determine the frequency of occurrences in an array where two elements are less than or equal to a specified sum - Using JavaScript

I've been working on a JavaScript function that counts the number of times two elements add up to a given sum. However, now I'm looking to modify this so that it not only considers when the two elements equal the sum, but also when they are less ...

Is it feasible to retrieve and view local storage data within an Electron application?

I created an electron application that enables users to drag and drop elements like divs on the screen, saving their positions in localstorage as a class. The purpose is to ensure that any modifications made by the user persist even after reloading or re ...

Ways to display a particular div when clicked and conceal the rest

I'm new to AngularJS and I'm trying to create 4 buttons. When a user clicks on a button, a specific div should be displayed while hiding the other 3 DIVs. Here is the code: <div class="active"> <button ng-click="a"><h5> ...