What steps do I need to take in order to design a directive that formats information while incorporating transcluded HTML

My goal is to create a directive that accepts an array or object as an attribute, allowing the user to customize the data formatting and styling. Although the directive is more complex than described here, it enables further data manipulation.

An example of what I'm trying to achieve:

The Custom Directive

angular.module('app').directive('myDirective', () => {
  return {
    template: '<h2>Your data:</h2><div><ng-transclude></ng-transclude></div>',
    restrict: 'E',
    transclude: true,
    scope: false,
    link: ($scope, $element, $attrs) => {
      $scope.people = $attrs.data;

      // Additional data processing can be done here
    },
    controller: ($scope, $element, $attrs) => {
      $scope.people = $attrs.data;

      // More processing can be done here as well
    }
  };
});

The Usage in View

<my-directive data="[{name: 'Tyler'}, {name: 'Mike'}, {name: 'John'}]">
  <ul>
    <li ng-repeat="person in people">{{person.name}}</li>
  </ul>
</my-directive>

I attempted to implement this but encountered issues with functionality. If anyone has suggestions on why this seemingly simple implementation isn't working, I would appreciate the guidance.

Answer №1

Before being transcluded into the directive, the markup passed to ng-transclude is already parsed. This means that it can access items on the scope outside of your directive. Even though you have set scope: false, allowing the directive to share the outer scope, the definition of scope.people only happens after the transcluded markup has been transcluded.

Angular creates a "transclusion scope" that initially inherits from the outer scope, giving you access to elements in that context. However, to prevent scopes from being destroyed when the directive's scope is destroyed, Angular replaces $parent with the isolate scope of the directive.

In essence, you should be able to retrieve data from the directive scope using the $parent property.

<my-directive data="[{name: 'Tyler'}, {name: 'Mike'}, {name: 'John'}]">
  <ul>
    <li ng-repeat="person in $parent.people">{{person.name}}</li>
  </ul>
</my-directive>

http://codepen.io/Chevex/pen/eJKBgj?editors=1010

Answer №2

One way to enhance this code is by passing the data into the directive's scope for easy reference as an object rather than a string:

scope: {
  info: '='
},

By doing so, you can perform various manipulations within the link/controller of your directive, and these changes will reflect in the transcluded content.

Check out this plnkr example to see how it works: http://plnkr.co/edit/RX2YljfpW45opqwertH8?p=preview

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

Navigate React interface through Express back end

Looking for a solution to redirect from my express backend in a react client. After exploring various posts, the method of inserting a redirect into the response body was unsuccessful. Ideally, I am seeking a way to handle redirection directly within the ...

Combining arrays based on a key in Node.js

I have the following two objects that need to be merged: [ { "response_code": 1, "response_message": [{ "a": 1000, "b": 1000001, "c": 10000002 }] }] [ { "response_code": 1, ...

When I use the jQuery foreach loop, I notice that it produces identical results for both values

Hey there, I'm encountering a new issue with this jQuery script. In my foreach loop, I am extracting the product names and descriptions. The problem arises when I have 2 distinct products with different descriptions, but the following code: <d ...

Enhance row visibility by clicking a button in an ajax table

I'm facing an issue where I am trying to apply a highlight class to the selected row in an ajax table when clicking on the edit button, but for some reason my code is not working as expected. Can someone assist me with this problem? Thank you in advan ...

Access the Express server by connecting to its IP address

Is it feasible to connect to an express server using the server's UP address? If so, how would one go about doing this? (Examples of code snippets would be greatly appreciated) ...

Double the Power of jQuery Live Search with Two Implementations on a Single Website

I recently implemented a JQuery Live Search feature that is working perfectly. Here is the JQuery script: <script type="text/javascript"> $(document).ready(function(){ $('.search-box input[type="text"]').on("keyup input", function(){ ...

Drag and drop non-event elements onto events using jQuery FullCalendar

I'm facing a challenge with dragging and dropping an employee name onto an event using jQuery UI draggable/droppable. I want to drag an employee (as shown in the picture) onto an event, but the 'employee' is not an event itself. <script& ...

What is the best way to trigger a function following a user's selection from a form-control on a webpage?

I am looking for a way to automatically execute a function when a year is selected without needing a button. I am using HTML, JavaScript, and bootstrap 5. Any suggestions on how to achieve this? Thank you. function onSelect() { console.log('Hel ...

Would it be better to lock a variable stored in req.session, or opt for a massive global variable instead?

As I delve into creating a game using node.js, the premise is sending units on missions and waiting for their return. The challenge lies in ensuring that the same unit cannot be sent on two different missions simultaneously, nor can two sets of units be di ...

Having trouble getting a Chrome extension/jQuery to work on certain sites but not others? Attempting to trigger an event when a link is clicked

For three different websites, I have three separate js files. I want to mention that the manifest has the correct settings to make sure these files work on the right sites, but unfortunately, only one function of the extension (the most important one) is n ...

Tips for keeping MUI Autocomplete open even when the input field loses focus

I am currently working with a MUI autocomplete feature that includes a list of items and an edit icon next to each one. The edit icon allows the user to change the name of the option by rerendering it as a textfield. However, I have encountered an issue wh ...

Access-Control-Allow-Methods does not permit the use of the PATCH method in AngularJS

Hello, I am currently attempting to send a PATCH request from AngularJS to ServiceStack and am encountering the following error: The PATCH method is not permitted by Access-Control-Allow-Methods. Here are the request headers: Connection: keep-alive Pr ...

The rejection of the WordPress custom plugin was due to the use of the reason 'Directly accessing core loading files'

I created a plugin for personal use and later decided to make it available to the public. However, my submission was rejected after a code review citing the reason ##Calling core loading files directly. I have addressed all the issues pointed out, except ...

Having some trouble in finding all the text within a label tag using Selenium Webdriver in Python

<label class="control-label"> Rental Charge: <span class="required" ng-show="vm.rentalInfo.reason">* (Minimum of $30.00)</span> </label> My approach was to use driver.findElement(By.xpath("//label[@class='control-label ...

JavaScript and jQuery experiencing difficulty rendering proper style and image in output display

I am currently working on code that extracts information from a JSON variable and displays it on a map. The code looks like this: marker.info_window_content = place.image + '<br/>' +"<h4>" + place.name + "</h4> ...

Receive user input from a button located within a table using modules in the R programming language

Currently, I am delving into working with modules in Rhino. My goal is to extract input from a button within a table when it is clicked. This module is responsible for creating the table and generating HTML buttons for each line item. # app/logic/fluxogra ...

Troubleshooting error message: "Unsupported import of ESM Javascript file in CommonJS module."

My project relies solely on CommonJS modules and unfortunately, I cannot make any changes to it. I am attempting to incorporate a library that uses ESM called Got library (https://github.com/sindresorhus/got). This is the snippet of my code: const request ...

Having trouble with the CKEditor character count function in JavaScript?

I integrated the Javascript and stylesheet from this source into my webpage. http://jsfiddle.net/VagrantRadio/2Jzpr/ However, the character countdown is not appearing on my site. What mistake have I made? ...

Filtering multiple values for end users in AngularJS

I am currently working on building an online shop platform with a filter feature for products. My goal is to allow users to select multiple options in the filter and display all items that match those selections. For example, if the checkboxes for "food" a ...

HTML card experiencing overlapping problem

I have a website with three columns using Bootstrap that contain images, each with a button in the center. I added a dialog window that should appear when a user clicks on a button within an image. However, the dialog window appears behind the columns and ...