Is there a way to render an ng-repeat comment in AngularJS after manual transclusion has taken place?

Snippet: http://plnkr.co/edit/zYd13f4EelPcQqJrguVh?p=preview

var app = angular.module("inputGroupApp", []);

app.controller('numbersController', ['$scope', function($scope){

  $scope.data = {}
  $scope.data.numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
}]);


app.directive('labelGroup', ['$compile', '$timeout', function($compile, $timeout) {
    return {
      'template'   : '<div class="label-group">' +
                     '<label class="label-group-label"></label>' +
                     '<div class="label-group-content"></div>' +
                     '</div>',
      'restrict'   : 'E',
      'transclude' : true,
      'replace'    : true,
      'link'       : function(scope, elem, attr, nullController, transclude) {

        var labelElem = elem.find('.label-group-label');
        var contentElem = elem.find('.label-group-content');

        transclude(scope, function(clone) {
          var tLabel = null;
          var tContent = null;

          angular.forEach(clone, function(node) {
            var $node = angular.element(node);

            // empty nodes by removing contents
          
            if ($node.is('label-group-label')) {
              tLabel = $node.contents(); 
              labelElem.append(tLabel);
            } else if ($node.is('label-group-content')) {
              tContent = $node.contents();
              contentElem.append(tContent);
            }
          });

          $compile(contentElem)(scope);

          console.log('contentElem ', contentElem);
          console.log('elem ', elem);
        });
      }
    };
  }]);

I am developing a directive to create a custom label and content pairing using transclusion. My goal is to have the transcluded elements compile successfully, especially when they include directives like ng-repeat. However, I am facing difficulties in getting the transcluded elements to render correctly. Any insights on resolving this issue would be greatly appreciated.

I may need to rethink my approach to solving this problem effectively.

Answer №1

After realizing that I was trying to make changes to the transcluded clone's DOM structure before compiling, specifically removing nested ng-repeat comments from their parent wrapper, it became clear why the ng-repeat wasn't functioning as expected - it had no scope data to repeat over and simply remained a comment.

The solution I found was to perform the compilation steps within the transclude function and then adjust the DOM by adding nodes outside of the transclude function.

Below is the updated code that appends the transcluded elements outside the transclude function and after they have been compiled:

http://plnkr.co/edit/E3Ha0xS6NUFIefohKve9?p=preview

var app = angular.module("inputGroupApp", []);

app.controller('numbersController', ['$scope', function($scope){

  $scope.data = {}
  $scope.data.numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
}]);


app.directive('labelGroup', ['$compile', '$timeout', function($compile, $timeout) {
    return {
      'template'   : '<div class="label-group">' +
                     '<label class="label-group-label"></label>' +
                     '<div class="label-group-content"></div>' +
                     '</div>',
      'restrict'   : 'E',
      'transclude' : true,
      'replace'    : true,
      'link'       : function(scope, elem, attr, nullController, transclude) {

        var labelElem = elem.find('.label-group-label');
        var contentElem = elem.find('.label-group-content');

        var tLabel = null;
        var tContent = null;

        transclude(scope, function(clone) {


          angular.forEach(clone, function(node) {
            var $node = angular.element(node);

            // these nodes have been emptied by gutting their contents
            // is it a memory problem that the nodes themselves aren't destroyed?

            if ($node.is('label-group-label')) {
              tLabel = $node.contents(); 
            } else if ($node.is('label-group-content')) {
              tContent = $node.contents();
            }
          });

          $compile(contentElem)(scope);
          $compile(labelElem)(scope);

        });

      contentElem.append(tContent);
      labelElem.append(tLabel);
      }
    };
  }]);

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

Check out the article on reading file uploads using jQuery or Javascript

I have a basic file upload field: <input type="file" id="signature" /> Here is the jQuery code I am using: $('#save').click(function() { var element = $('#signature'); if (element.files && element.file ...

Exploring the functionality of the JavaScript Date constructor in relation to

Will using new Date('2015-01-01') provide me with the exact moment equivalent to 2015-01-01T00:00:00Z? ...

Vue components are unable to access data within methods or computed properties

Within my Vue component, I initially set a boolean constant in the data object with a value of false. Now, I aim to create a method that will change this constant to true and conditionally bind certain elements in the template based on this change. Howev ...

What mechanism does the useState() function utilize in React to fetch the appropriate state object and function for a functional component when employing the state hook?

Currently focusing on deepening my understanding of the useState hook in react. I have a question regarding how useState retrieves the state object and modifier function specific to each functional component when it is called. What I'm wondering is w ...

Deciding which HTML element to display in AngularJS

What is the method of selecting which HTML element to display in AngularJS? When retrieving a value from the database, if it is YES, I would like to display this: <i class="fa fa-check"></i>, otherwise display this: <i class="fa fa-times"& ...

The unresponsive switch

Hello all, this may be a silly question but bear with me... I've encountered an issue with the following block of code: var clicks = 0; $('body').click(function(){ clicks ++; console.log(clicks); }); switch(clicks){ case 1: ...

How can I prevent media controls from appearing in fullscreen mode on Microsoft Edge using CSS?

My video code allows for switching the video into fullscreen mode using custom controls. Here's how it looks: fullScreenButton.addEventListener("click", function() { if (video.requestFullscreen) { video.videoContainer.r ...

Anticipated spatial glitch problem involving the gadicc/meteor-reactive-window package for Meteor

Utilizing the gadicc/meteor-reactive-window Meteor Package to switch templates based on screen size. This file is named pictureDisplatSection.html <template name="pictureDisplaySection"> <div class="display"> ...

Implementing a dynamic background change based on the current date in JavaScript

Is it possible to change the background of the body element based on the season using JavaScript? Here is a code snippet that demonstrates how to achieve this: // Function to determine the current season in the southern hemisphere // If no date is prov ...

angularjs ngmodel directive with dual values

I need help with customizing my dropdown control <div ng-repeat="prop in props" style="margin-bottom: 10px;"> <label class="col-md-4 control-label">Property {{$index + 1}} ({{prop.Value}})</label> <div class="col-md-8"> < ...

Exploring the process of querying two tables simultaneously in MySQL using PHP

I currently have a search box in my PHP file that only searches from the "countries" table. However, I also have another table called "continent" and I would like the search box to retrieve results from both the "countries" and "continent" tables. Here is ...

When I tap on it, the box should shift its position

Here's a conundrum for you. I have a box that I want to move 200px to the left when clicked, but I'm struggling to make it work. Can someone please lend a hand and point out where I'm going wrong? <style> .box { width: 200px; ...

React Native Issue: Missing propType for native property RCTView.maxHeight

Upon upgrading to RN 0.30, I encountered the error message below even when trying to build the most basic app: react-native init AwesomeProject react-native run-ios What's peculiar is that the warnings include components BlurView, VibrancyView, an ...

Eliminate JSON data that pertains to dates that are either in the past or future

I am working on integrating upcoming classes and past classes components into my application. I have successfully stored the schedule of classes and can retrieve them using backend services. However, I need to display only the upcoming classes in one compo ...

The system was unable to locate the URL property as it was undefined

Having followed a brief tutorial, I created this widget script to fetch posts from Blogger. Initially, it worked flawlessly without any errors in the theme that I designed it for. However, upon attempting to use the same code in a new template that I am cu ...

Resetting JavaScript timer from AS3 using ExternalInterface.call

I'm currently working on implementing a 'dead man's switch' feature in a flash application. The goal is to have the webpage automatically refresh if the app crashes or experiences significant slowdown. After researching, I found out tha ...

Obtain the URL value using jQuery and place it inside a <span> element

How can I insert a href value into the span tag like this? <p class="name"> <a download="adja-lo.pdf" title="adja-lo.pdf" href="http://localhost/MatrixDRSnews/apps/Matrix/server/php/files/adja-lo.pdf">adja-lo.pdf</a> </p> ...

What is the best way to send an array to the Mailgun API using HTTP POST in an Ionic 5 application?

I have been attempting to send URLs of images to the Mailgun API in order to utilize them as variables in my Mailgun Email Templates. Unfortunately, I am facing difficulties figuring out how to do this. While I can use 'v:' to pass single variabl ...

Getting the index value for an entire table involves retrieving the position of each row

Right now, I have set it to display 5 rows per page. However, when I check the index of the table on the first page, it shows indices 0 to 6 for that page. The same thing happens on the second page - again showing indices from 0 to 6. I am trying to figure ...

JavaScript document string separation

Hi there, I'm a newbie here and could really use some assistance. I am struggling with creating a function and would appreciate any ideas... To give you an idea of what I need help with, I have a String and I want to check if it contains a specific w ...