Utilizing Angular Directives and Transclusion in ngRepeat

I am facing an issue with transclusion within the ng-repeat directive in Angular. The problem arises because Angular is unable to find the .transclude element within the template, leading to the replacement not taking place. I suspect that this issue occurs because ng-repeat removes the .transclude before the transclusion process. I am seeking a solution on how to perform the replacement before ng-repeat manipulates the placeholder or any other workaround for this problem.

Side note: If I switch to using the ng-transclude directive, the code works correctly. However, it requires me to access values using $parent {{$parent.item.name}}, which is not ideal for me.

Below is the condensed version of my code:

HTML

<div mydir="items">
    {{item.name}}
</div>

template.html

<div ng-repeat="item in items">
    <div class="transclude"></div>
</div>

Directive

app.directive("mydir" , function(){
    return {
        templateUrl : "template.html",
        transclude : true,
        scope : {
            items: "=mydir"
        },
        link : function($scope , $element , attrs , $ctrl , $transclude){
            $transclude(function($content){
                $element.find(".transclude").replaceWith($content);
            });
        },
    };
})

Expected Result Before Compilation

<div mydir="items">
    <div ng-repeat="item in items">
        {{item.name}}
    </div>
</div>

Answer №1

If you're looking for a solution to achieve your goal, I have an option that might work for you. It involves extracting the content of the {{ item.name }} in your HTML directive and creating a dynamic template using the compile function of the directive.

var app = angular.module('plunker', []);

app.directive("mydir" , ['$compile', '$templateRequest', function($compile, $templateRequest){
    return {
        scope : {
            items: "=mydir"
        },
        compile: function($element) {
          var transclude = $element.html();
          $element.html('');
          return function(scope, elem) {
              $templateRequest("template.html").then(function(html){
                  var tpl = angular.element(html);
                  tpl.children('.transclude').append(transclude);
                  $compile(tpl)(scope);
                  elem.append(tpl);
              });
          };
        }
    };
}]);

app.controller('MainCtrl', function($scope) {
  $scope.items = [{
    name: "Item 1"
  },{
    name: "Item 2"
  }]
});

Feel free to check out the 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

Tips on configuring a hidden input field to validate a form

I am currently attempting to create a blind input field using PHP that will validate if the input field is empty. If it's not empty, the message set up to be sent will not send. However, I have encountered several issues with the placement and wording ...

Is there a way to activate calculations whenever one of two inputs change, while also ensuring that one input is always lower than the other using a directive?

I have a directive called kcInputComparer which includes a validator named lessThan. I applied this directive to one input field, comparing its value to a second input field. When I modify the value in the first input field, the validator functions correct ...

Implementing Google Calendar access token in JavaScript: A practical guide

I have a question about Google Calendar and I'm hoping you can assist me. I currently have an access_token from Google Calendar that has been stored in the localStorage. const googleAccessToken = e.vc.access_token; localStorage.s ...

Upon initial launch of the application, JavaScript fails to load

I am currently working on developing a hybrid app that utilizes iOS as the native platform and Cordova-Phonegap for HTML support. Upon launching the application for the first time, we encounter an issue where the JavaScript fails to load. Although we are ...

What is the best way to save an image in Node.js?

While I am extracting data from a website, I encountered the need to solve a captcha in order to access further data. I thought of presenting the captcha to the user, but the site is built using PHP and PHP-GD, complicating the process. The URL provided in ...

What could be causing the ternary operator to default to true?

I came across this snippet of code: const production = process.env.PRODUCTION console.log(production) const corsOptions = { origin: production ? 'https://myproductionurl' : 'http://localhost:3000', credentials: true } console. ...

MulterError: Files must be uploaded to designated folders, found at wrappedFileFilter. Detected issue with 2 files

Initially, I want to express my apologies for any language mistakes in this message. I am currently facing difficulties with file uploads using Multer and Express. The issue arises when attempting to upload two files to separate directories; consistently ...

Angular- linking form submission to various buttons

I have a form that includes several submit buttons: <form name="myForm" customSubmit> <input type="text" ng-minlength="2"> <button type="submit" ng-click="foo1()"></button> <button type="submit" ng-click="foo2()"> ...

Navigate through each file or image within a directory using Angular

I am facing a challenge with my app where each product has a gallery containing a random number of images, each with a completely unique name. These images are located in /src/assets/images/products/:id/. Currently, I am struggling to loop through and add ...

"Composing perfect sentences: The art of incorporating quotes

I am attempting to include text with quotes in a DIV, like so: "All is well that ends well" The text is generated dynamically and I'm using a JavaScript font replacement plugin (CUFON) to add quotes around the text. Sometimes, the ending quote drops ...

Listener for body keystrokes

Is there a way to trigger a function when the space bar is pressed on the page, without it being called if an input field is focused? Any thoughts or suggestions? The current code triggers the function even when an input bar is focused: $(document).keydo ...

What is the best way to retrieve the IDs of selected items in jQuery selectables?

I have a straightforward question that I've been struggling to find an answer to. When using jQuery selectables, I want to retrieve the ID of the selected list item when it's clicked. Here is an example of my list: <ol id="selectable"> ...

Encountering the error message "Attempting to open an unclosed connection" when invoking a function from a child process in Node.js

I keep encountering the issue of "Error: Trying to open unclosed connection," even though I don't think it's related to a database problem. This has me puzzled because most fixes for this error point towards database connection troubles. My obje ...

transfer information to the $_POST array using AJAX

When I click the 'submit' button to start playing music, my form data is not being sent to the global array $_POST. How can I fix this issue? Should I consider using AJAX and how would I implement it? The music plays, but the form data isn't ...

What steps can I take to reset my JavaScript code once its original purpose has been fulfilled?

I created this code, learning as I went along. It measures Beats Per Minute as one clicks the left-mouse-button each time they feel a pulse. After 10 clicks, the JavaScript code takes all the values in the array and calculates an average BPM. The issue ar ...

Adjust the color of a contenteditable div once the value matches

I currently have a table with some contenteditable divs: <div contenteditable="true" class="change"> This particular JavaScript code is responsible for changing the color of these divs based on their content when the page loads. However, I am now ...

Error in template loading

Currently, I am going through the Angular.js tutorial to learn how to incorporate some of its advanced features into my existing applications. Everything has been smooth sailing until I reached the (angular route) section. Unfortunately, I've hit a ro ...

Stop editable div's function of processing specific characters while typing

Recently, I came across some interesting code shared by Pranav C Balan in response to my query on this particular issue: var div = document.getElementById('div'); div.addEventListener('input', function() { var pos = getCaretCharac ...

Adjust the size of the iframe image to fit seamlessly within the design

Is there a way to adjust the size of the image on the right without altering the layout design? The current GIF is 500x500px, but it is only displaying as 100x100px. Any assistance would be greatly appreciated! To see what I currently have (Demo with code ...

Nuxt and Webpack error: Failed to parse module - Unexpected character (1:0)

https://i.sstatic.net/ope8z.png I am working on a Vue carousel component and my goal is to dynamically generate a list of .png files from the static folder. I have followed instructions from here and also from here. Below is an excerpt from my component: ...