Using ng-transclude directive allows for encapsulating HTML content within an ng-transclude element

My directive includes an ng-repeat in the template and also has an ng-transclude option after the repeater to allow users to input their own content. The issue arises when the custom content is surrounded by an ng-transclude element upon rendering, which is not desired.

This is how the directive looks:

angular.module("MyModule", [])
  .directive('myDirective', [function () {
    return {
      restrict: 'EA',
      transclude: true,
      replace: true,
      scope: {},
      templateUrl: 'templates/template_view.html',
      link: function (scope, element, attrs) { 
        scope.nodes = [
          {
            "imageSource": "",
            "title": "Sample Title",
            "body": "Lorem ipsum and some other stuffs",
            "readMore": "",
            "date": "Mar 20"
          }
        ];

      }
    };
  }]);

This is the template code:

<section>
  <div class="someClass" ng-repeat="node in nodes">
    <div>
      <img src="{{node.imageSource}}" alt="Picture">
    </div>
    <div class="content bounce-in">
      <h2>{{node.title}}</h2>
      <p>{{node.body}}</p>
      <a href="{{node.readMore}}" ng-show="{{node.readMore}}">Read more</a>
      <span>{{node.date}}</span>
    </div>
  </div>
  <div ng-transclude></div>
</section>

To use the directive, you can follow this example:

<div my-directive>
  <div class="someClass">
    <h2>Title of section 1</h2>
    <p>Lorem ipsum dolor </p>
    <span class="cd-date">Jan 14</span>
  </div>
  <div class="someClass">
    <h2>Title of section 2</h2>
    <p>Lorem ipsum dolor</p>
    <span class="cd-date">Jan 18</span>
  </div>
</div>

The output may include an unwanted <div ng-transclude> element wrapping the transcluded data.

Answer №1

To utilize the transclude function provided to your directive's controller and link functions, especially the link function which is the recommended approach, refer to the Angular docs. You will receive a clone of the transcluded content that allows you to manipulate it as needed.

angular.module("MyModule", [])
  .directive('myDirective', [function () {
    return {
      restrict: 'EA',
      transclude: true,
      replace: true,
      scope: {},
      templateUrl: 'templates/template_view.html',
      link: function (scope, element, attrs, ctrls, transcludeFn) { 
        scope.nodes = [
          {
            "imageSource": "",
            "title": "Sample Title",
            "body": "Lorem ipsum and some other stuffs",
            "readMore": "",
            "date": "Mar 20"
          }
        ];
        
        transcludeFn(function (clone) {
          element.find('a-selector-for-the-ng-translude-element').after(clone).remove();
        });

      }
    };
  }]);

This code has not been tested...

Additionally, rethink the use of replace: true as it has been deprecated since Angular 1.3

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

How can I implement a loop using .then in JavaScript?

Looking to understand the .then concept in JavaScript, I am curious if it is feasible to generate a series of .then's using a for loop. request.send(myRequest) .then(r => console.log(r, 0)) .then(r => console.log(r, 1)) .then(r => ...

Searching for data between two specific dates can be achieved in Laravel Vue by utilizing the filter

I've successfully implemented a search feature for normal fields in my form. However, I'm encountering difficulty when trying to search within a date range. Here's my controller code: public function index() { $query = Matter::query(); $qu ...

receiving an undefined value from a remote JSON object in Node.js

I have been struggling to extract the specific contents of a JSON api without success. Despite my best efforts, the console always returns undefined. My goal is to retrieve and display only the Question object from the JSON data. After spending several h ...

I am having trouble with json_encode in my Symfony2 controller

Just starting out with Symfony2 and AngularJS. Trying to use json_encode to display content from my database, but running into issues. Here's my controller: public function catalogonewAction() { $data = $this->getDoctrine()->getManager() ...

The dimensions of the image are determined by its orientation

I am working with two different types of images on my website: vertical and horizontal. Currently, I have a JavaScript function that adjusts the height of all images to fit the screen size. However, I would like to modify this function so that it also adap ...

The v-autocomplete feature in vuetify doesn't allow for editing the text input after an option has been selected

Link to code on CodePen: CodePen Link When you visit the provided page and enter "joe" into the search box, choose one of the two Joes that appear. Try to then select text in the search box or use backspace to delete only the last character. You will no ...

Removing a function when changing screen size, specifically for responsive menus

$(document).ready(function () { // retrieve the width of the screen var screenWidth = 0; $(window).resize(function () { screenWidth = $(document).width(); // if the document's width is less than 768 pixels ...

Having issues with the custom listing feature in Jquery UI auto complete not functioning as expected

I am facing an issue with my implementation of jquery UI autocomplete. The autocomplete functionality is not working as expected, despite the absence of any JavaScript errors. Below is the JSON data that I am working with: {"d":"[{\"label\":&bs ...

How can we show a React JS component when clicked, without using the App.js file for display?

How can I display a component onclick in React JS without using UseState in a file other than App.js? This code will be in App.js var [clicks, setClicks] = useState(false) return( <> {clicks && &l ...

Updating an Angular $watchCollection when modifying an Attribute: A step-by-step guide

Hey there, I've encountered a small issue while updating an attribute of an array of objects in my parent controller. The $scope.items variable holds an array of objects. $scope.items = Ticket.items; $scope.$watchCollection('items', funct ...

Animate elements in Vue.js when navigating between pages is a great way to enhance user

I'm looking to add animation to a specific element once the route page finishes loading. This is not related to route page transitions. I've experimented with various methods, trying to animate a progress bar based on dynamic data values. I attem ...

Is converting the inputs into a list not effectively capturing the checkbox values?

On my website, I have a div that contains multiple questions, each with two input fields. When a button is clicked, it triggers a JavaScript function to add the input values to a list. This list is then intended to be passed to a Django view for further pr ...

Manipulating div positions using JQuery and CSS

Whenever I hover over the #HoverMe div, a hidden #hidden div appears, and when I unhover it, the hidden div disappears again. The #hidden div contains a sub-div that functions like a dropdown list. The #hidden div is styled with position: absolute;. How ca ...

The background image fails to show up on the mobile device display

Currently, I am working on an app with Ionic, but unfortunately, the background image is not showing despite all my efforts. I have gone through various solutions provided in previous questions, but none of them seem to work for me. Here is the CSS I am u ...

How can I use JavaScript to consistently fetch the CSS-defined percentage setting for padding/margin instead of the pixel size?

How can I retrieve the padding set in CSS for a div with {padding:10% 10px 20% 10px;} using JavaScript, considering that window.getComputedStyle(myelement).getPropertyValue('padding'); returns different results? In Firefox, it shows as "10% 10px ...

When outputting the $http response in the console, Angular displays null instead of the expected result,

I have encountered a peculiar issue with my local webservice developed using Spring. Everything seems to be functioning correctly when accessing it through the browser or Postman, but for some reason, when attempting a simple GET method with Angular/Ionic, ...

Making a secure connection using AJAX and PHP to insert a new row into the database

Explaining this process might be a bit tricky, and I'm not sure if you all will be able to assist me, but I'll give it my best shot. Here's the sequence of steps I want the user to follow: User clicks on an image (either 'cowboys&apos ...

Using JQuery to fill an HTML dropdown menu with data from a JSON file

I've been struggling with this issue for a while and despite reading through other posts, I still can't seem to get it to work. My problem lies in populating a drop down menu with JSON data. Although the drop down menu appears on my HTML page, i ...

Navigating to a different state key within a state object in React - a simple guide

Trying to dive into React, I encountered an issue. My goal is to create my own example from a tutorial. import React, { Component } from 'react'; class MyComponent extends Component { state = { persons: [], firstPersons: 5, variab ...

How can I make a dropdown menu appear when I select a checkbox?

Is it possible to have a dropdown menu with changing options appear when I click on a checkbox using HTML and JavaScript? I have experimented with some code snippets in JavaScript as a beginner, but I am unsure if they are needed here. Is there an altern ...