Using AngularJS to transclude ng-repeat within a directive

I have created a custom directive that transcludes the original content, parses it, and uses the data in the original content to construct the new content. The main concept behind it is as follows:

.directive('customList', function() {
    return {
        restrict: 'E',
        transclude: true,
        templateUrl: '...',
        scope: true,
        controller: function($scope, $element, $attrs, $transclude) {
            var items;
            $transclude(function(clone) {
                clone = Array.prototype.slice.call(clone);
                items = clone
                    .filter(function(node) {
                        return node.nodeType === 1;
                    })
                    .map(function(node) {
                        return {
                            value: node.getAttribute('value')
                            text: node.innerHTML
                        };
                    });
            });

            // Conduct further actions with the item data here
        }
    }
});

Subsequently, I implement it like so:

<customList>
    <item value="foo">bar</item>
    <item value="baz">qux</item>
</customList>

Everything functions properly in this manner. However, issues arise when attempting to apply an ng-repeat within the directive content, such as:

<customList>
    <item ng-repeat="item in items" value="{{ item.value }}">{{ item.text }}</item>
</customList>

When trying this approach, there are no displayed items. Could anyone shed light on why this may not be functioning correctly, or suggest alternatives for achieving the same outcome?

Answer №1

If you're looking to experiment with:

transcludeFn(scope, function (clone) {
   iElem.append(clone);
})

For a more in-depth explanation:

HTML:

<foo data-lists='[lists content here]'>
 <li ng-repeat="list in lists">{{list.name}}</li>
</foo>

Directive:

var Foo = function() {
  return {
     restrict: 'E',
     template: '...'
     transclude: true,
     scope: { lists: '=?' }
     link: function(scope, iElem, iAttrs, Ctrl, transcludeFn) {
          transcludeFn(scope, function (clone) {
              iElem.append(clone);
          }
     }
  };
};

.directive('foo', Foo);

You should notify transcludFn about the scope you intend to utilize within transcludeFn. And if isolate scope is not preferred, you can also attempt transcludeFn(scope.$parent....)

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

Changing return values with Jest mocks in TypeScript

Here I am again with a very straightforward example. In summary, I require a different response from the mocked class. Below is my basic class that returns an object: class Producer { hello() { return { ...

Utilizing the Angular directive known as "ng-repeat" enclosed in quotation marks

I'm currently working with the metro ui framework and attempting to use ng-repeat to generate HTML within a popup. The template I'm using is shown below. Any suggestions or advice would be greatly appreciated. I have confirmed that the data is p ...

Struggling to display my JSON file in an HTML element with AJAX

Having some trouble here. I can successfully print my JSON file content to the console using console.log, but now I'm trying to display it on the page. I want to display the 'Information' section from the JSON file using innerHTML like this ...

Issue with Bootstrap Table Style When Using window.print();

The color of my Bootstrap table style is not displaying correctly in the print preview using window.print(). Here is a screenshot showing that the table style is not working properly: https://i.stack.imgur.com/eyxjl.jpg Below is the code I am using: < ...

Error occurs when a handlebar helper is nested too deeply

I have set up two handlebar helpers with the names 'outer' and 'inner'. In my template, I am using them as shown below: {{#outer (inner data)}} {{/outer}} However, I am encountering an error in the console related to the inner helper, ...

Is Ruby on Rails featured in Designmodo's Startup Framework Kit?

I'm curious if the Startup Framework Kit from Designmodo can be seamlessly incorporated into my Ruby on Rails project. While I've had success integrating their Flat-UI-Pro using a gem, I haven't come across one for the Startup Framework yet. ...

Using regex, match any word along with the preserved white space and consider parentheses as a single word

I need help with creating a regex pattern to split a string of words in a specific way. The current pattern I've been using is (?!\(.*)\s(?![^(]*?\)), but it's not giving me the desired outcome. It's close, but not quite the ...

Guide on integrating database information into an array with Vue.js

I'm having trouble retrieving data from Firestore and applying it as my array. I expect to see objects in the console but nothing is showing up. Should the method be called somewhere in the code? My method created() is functioning, but only when I han ...

Issue with TextField not transitioning to dark mode in MUI5.0

I've been struggling to turn a MUI <TextField /> to dark mode. Despite trying various solutions such as using ThemeProvider and CSSBaseline, I haven't been able to achieve the desired result! I have attempted the code below and researched ...

Steps to Display a Popup When an Asp.Net Button is Clicked

One feature I am working on involves a popup that will display a message to the user confirming that their information has been successfully submitted. The ID of this popup is NewCustomerStatusPopUp, and I want it to be triggered once the information has b ...

Tips on deleting the last character in an input field with AngularJS

Can you help me with the title of this question? I'm currently working on developing a straightforward calculator using AngularJS. It's operational at the moment, but I'm looking to incorporate additional buttons like a "delete" key and a de ...

A collection of dropdown fields sharing identical names but containing distinct IDs

I am looking to create an array of select fields with the same list of option values. The goal is to prevent a value that is selected in one field from appearing in another field. For example, if "a" is selected in the first field, it should not be avail ...

Discovering the Harshad number

I find myself in a predicament where the issue at hand is defined as: Harshad/Niven numbers are positive numbers that are divisible by the sum of their digits. All single-digit numbers are Harshad numbers. For instance, 27 is a Harshad number as 2 + 7 = ...

What could be causing the buttons in this JavaScript trivia game to consistently show the wrong answer even after selecting the correct one?

My latest project involves creating a trivia game using vanilla JavaScript and Bootstrap. The game fetches questions from the API, displays the question along with four multiple choice answers on separate buttons using Bootstrap. To ensure the buttons are ...

The method is unable to assign a value to the undefined property 'var'

I am encountering a simple issue that is giving me an error message TypeError: Cannot set property 'question' of undefined at setQuestion I am struggling to identify the root cause of this problem. As I am new to AngularJS, I wonder if ...

What is the best way to showcase five products in a row instead of four on the "featured" section of the homepage?

Seeking help with administration: Looking to display five equal columns in Twitter Bootstrap. The solution provided does not work for me because I cannot simply duplicate it 5 times. It seems that the OpenCart "featured" module operates using a loop, but I ...

Using Node.js to lazily load Ext JS Tree data from a MySQL database

I have developed an application where Node.js serves as the backend and Extjs as the Frontend. One of the challenges I am facing is constructing a tree in Extjs using Database values retrieved from Node.js. Currently, I can successfully build the Tree st ...

Is there a method or API available for interacting with an <object> that is currently displaying a video?

Yay, I figured it out! I've been using video.js to play videos on a website that needs to work offline too. Unfortunately, using flash is not an option due to compatibility issues. So, I decided to write my own fallback solution. For Internet Explor ...

Error: The navigation property is not defined - React Native

Utilizing Firebase in combination with react-native for user authentication. The main file is App.js which directs users to the Login component and utilizes two components for managing routes: Appnavigator.js to create a switchNavigator and DrawerNavigator ...

Utilize an asynchronous factory service within another asynchronous service for seamless integration

My task involves the following steps: Initiating a query to an API for a large dataset of names, possibly through a service/factory, using $q (async) Implementing another service (also async) that will filter elements from the above factory based on a ...