Transcluding an element into an ng-repeat template in AngularJS: How can it be done?

Incorporating a carousel directive involves chunking the passed in array of items and mapping it into an array of arrays of elements. This structure then generates markup resembling the pseudo code provided below:

<array of arrays>

  <array of items>
    <item>
    <item>
  </array of items>

  <array of items>
    <item>
    <item>
  </array of items>

</array of arrays>

The angular template designed for this scenario is as follows:

<div class="carousel__content" ng-style="carousel.containerWidth">
  <ul class="carousel__chunk" ng-repeat="chunk in carousel.chunks" ng-style="carousel.chunkWidth">
    <li class="carousel__item" ng-repeat="item in chunk" ng-style="carousel.itemWidth">
      <div class="carousel__item-content">

        [element to be transcluded here.]

      </div>
    </li>
  </ul>
</div>

Using the following view code:

<!-- Ensure that the <a> tag appears within the 'carousel.html' template's ng-repeat list. -->
<carousel items="items" config="config">
  <a href="#">{{ item.name }}</a>
</carousel>

The objective is to have the transcluded element bind to the item object of the deepest ng-repeat.

A comprehensive Plunker showcasing a simplified test case can be accessed via this link: http://plnkr.co/edit/kYItcXV0k9KvnpiYx1iG

The issue arises from the inability to insert an ng-transclude attribute within the ng-repeat. Additionally, efforts to manually inject the transcluded markup at that location using the transclude() function in the compile phase of the directive as demonstrated in the carousel.js directive file in the Plunkr, have proven unsuccessful.

Any suggestions or solutions would be greatly appreciated.

Answer №1

To make the transclusion function accessible, set a variable within the link function of your directive:

 post: function($scope, $element, attrs) {
     $scope.transclude = transclude; 
     ...

Next, create a new directive called innerTransclude to replace ng-transclude on the element where you want the transcluded content to appear:

.directive('innerTransclude', function(){
  return function(scope, elem, attrs){
    scope.transclude(scope, function(clone){
      elem.append(clone);
    });
  }
})

This directive simply appends the cloned content to the element, avoiding any issues with nested transclusions. Don't forget to include it in your template:

<div class="carousel__item-content" inner-transclude></div>

Check out the Demo for more information.

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

What is the best way to extract the event time when a user clicks on an event in fullcalendar?

Is there a way to extract only the time from an eventclick event in fullcalendar? Currently, I am receiving details about the event including date and time. How can I specifically retrieve just the time (e.g. 6:00:00 am)? You can find the code snippet tha ...

Introducing a delay in an observable causes incomplete data to be received in Angular using rxjs

Currently, I am facing an issue in my code where I am trying to introduce a delay using timer(500). However, the problem is that it is only returning partial data. Instead of the expected 17 fields, it is only returning 2 fields. Below is my code snippet f ...

FF and IE9 cause issues with Backbone application

I recently finished developing a web application using Backbone, ICanHaz, and jQuery. If you want to check it out, click on this link: While the app works flawlessly in Chrome (version 12.0.742.122), it encounters issues in Firefox 5 (5.0.1) and Internet ...

The z-index overlapping problem in webkit browsers is a result of Angular 7 animations

I have implemented staggered animations in my Angular 7 application to bring elements to life upon page load. However, I am facing a strange z-index problem with one of my components. Here is the animation code: @Component({ selector: 'track-page& ...

AngularJS $location Redirect Error: Property 'path' Undefined

I'm struggling with an issue in my AngularJS code where I am trying to change the URL without reloading the page when a submit button is clicked. However, I keep getting a TypeError: Cannot read property 'path' of undefined in the console. ...

Encountering an issue in a Next.js application while building it, where an error is triggered because the property 'protocol' of 'window.location' cannot be destructured due to being undefined

While building my nextjs application, I encountered the following error. My setup uses typescript for building purposes, although I am only using JavaScript. Build error occurred: TypeError: Cannot destructure property 'protocol' of 'window ...

Is it considered secure to replace an object within an array when working with Angular bindings?

In my Angular JS project, I have incorporated a form with a reset function. Whenever I begin editing an item on the form, the setPrimarySelectionEditEntry function is invoked. The primarySelectionEntry variable contains the object bound to the controls. ...

Unable to showcase Angular model in an alternative view

I'm currently working on a sample application where I need to display my model in one view and allow editing in another. Here's the controller code I'm using: var app = angular.module('plunker', ['ngRoute']); app.contro ...

What is the best way to simulate a constructor-created class instance in jest?

Suppose there is a class called Person which creates an instance of another class named Logger. How can we ensure that the method of Logger is being called when an instance of Person is created, as shown in the example below? // Logger.ts export default cl ...

In JavaScript, I would like to be able to input an end date and have the program calculate and display the number of days remaining until the deadline

I'm working on a school project that involves JavaScript code. I'm struggling with converting a date prompt from string to number format. As a beginner in JavaScript, I could really use some guidance. <script> enddate = prompt('Wh ...

An issue with the function in AngularJS has caused an undefined error

Encountering an error in my AngularJs app that states: TypeError: undefined is not a function at Scope.$rootScope.shareImageNow (index.controller.js:150) After researching on Google, I still couldn't figure out the reason behind this issue. co ...

Adding an exception for ClickAwayListener in React-MUI

Hey there! I'm currently exploring MUI and trying to incorporate the ClickAwayListener API into my project, but I'm facing some difficulties. You can take a look at my project on codesandbox here: https://codesandbox.io/s/react-leaflet-icon-ma ...

Expressjs Error- ReferenceError: cors has not been defined in this context

While working on creating a backend using ExpressJs, I encountered an error when running the backend. app.use(cors()) ^ ReferenceError: cors is not defined at Object.<anonymous> (C:\Users\hp\Desktop\Entri\kanba\ ...

Exploring through a table using JavaScript

I am struggling to search a table within my HTML for a specific term. The code I have works to an extent, but it does not account for alternatives such as searching for "what is that" when I type in "What is that". Additionally, I need the script to ignor ...

Adjust CardMedia Images to match their content in the new MUI 5 version

I’m looking to have my images fully fill the CardMedia component. However, because they are of varying sizes, some end up being cropped like this: https://i.stack.imgur.com/JHIrT.png Additionally, when resizing the images, some get cut off as well: ht ...

How does the question mark symbol (?) behave when utilizing it in response? Specifically in relation to data, the API, and the fetch API

Have you encountered the curious sequence of symbols in this context? data?.name Could you explain the significance of the question mark (?) between 'data' and the period? ...

I encountered an issue while making customizations to my default next.config.js file. Despite attempting various solutions, I consistently encountered an error regarding the invalid src property

I'm currently trying to introduce some custom configurations into the next.config.js file. However, I keep encountering an error regarding an invalid src prop. Despite my attempts to troubleshoot in various ways, the error persists. // ...

The Toggle Functionality necessitates a double-click action

I'm currently working on implementing a menu that appears when scrolling. The menu consists of two <li> elements and has toggle functionality. Everything is functioning properly, except for the fact that the toggle requires two taps to activate ...

Vue email validation is failing to return a valid email address

I'm relatively new to Vue and have implemented email validation using the reg expression in my Vue script data for this project. By utilizing console.log(this.reg.test(this.email)) and observing the output while users input their email, the validation ...

The behavior of the 'typeof null' function in JavaScript is not functioning

I have a collection of objects where each object contains a key and an array as a value. You can see what I mean in this image. Some of the arrays had less than 20 elements, so I wrote some code to pad them with zeros. The result of running my code can be ...