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

Testing an AngularJS controller that relies on route resolution is an integral part of the development

I am having difficulty writing unit tests for my controller because it relies on data that is fetched when the route is resolved. I need to find a way to test this without encountering errors related to missing "locals". The controller code snippet: myMa ...

Angular: issue with accessing deferred variable within then-method

When working with my Angular.JS code, I encountered an issue while calling the Yahoo YQL API using GET/JSONP. Although I receive a response, there are two specific problems that arise. Instead of triggering the success method, it calls the error method. ...

Troubleshooting Tips for Node.js and MongoDB Socket Closure Issue

I'm running into an issue while working on the login system for my NodeJS application. Everytime I attempt to retrieve a collection, MongoDB throws me this unusual error. The Error Message [MongoError: server localhost:27017 sockets closed] name: &a ...

What is the most efficient way to use jQuery to retrieve the count of tags associated with a variable

I am trying to filter my data retrieved from ajax using a function. Here is the initial code: var csvf = data.filter(function (el) { return ['TRUCK_CPX'].indexOf(el.TAG) >= 0 && ['CA5533'].indexOf(el.Chave) >= 0 }); Now ...

JavaScript array contains duplicate values

I have developed a custom Asp.Net user control. To keep things simple, I have omitted some of the HTML code. <asp:Panel ID="PanelInputControl" runat="server" CssClass="input-control input-period"> <div ID="InputWrapperMonth" runat="server" c ...

Enhance User Experience with ngDialog Modal's Multi-pane Feature for Angular

Looking at the ngDialog example, they showcase a modal with multiple 'panes' that can be scrolled through: . After going through the ngDialog guide, I couldn't find a straightforward way to achieve this. Any suggestions on how to add a butt ...

Issues with Select2 Ajax functionality not functioning as intended

I am currently using the select2 library to create a dropdown menu with ajax functionality, but I am encountering some issues. Below is my code: $("#guests").select2({ multiple: true, minimumInputLength: 1, formatInputTooShort: fun ...

Error encountered: Invalid symbol detected ('<') while attempting to parse JSON in an Angular application

I am experiencing an issue with my Angular code when trying to submit a form. Upon clicking the submit button, an error saying JSON Parse error: Unrecognized token '<' appears, and empty records are being saved in the database. I have included ...

User authentication using .pre save process

I have an API that accepts users posted as JSON data. I want to validate specific fields only if they exist within the JSON object. For example, a user object could contain: { "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" dat ...

Uncover and control nested objects in JSON data

Having a dynamic foo object with the possibility of nested parent objects raises the question of how to effectively: 1) Determine the last object that has a parent? 2) Create an array containing all nested parent objects along with the initial obj (foo.o ...

Troubleshooting problems encountered in Nest.js due to modifications made within a service.ts file

I'm currently working on a Nest.js project and here is the content of the automobile.service.ts file: import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Car } from './enti ...

ReactJS: Trouble encountered while parsing information from JSON data

Currently, I am facing an issue while trying to pass data from my JSON file to my ReactJS application. The error message that I am encountering is as follows: TypeError: Cannot read property 'mainPage' of undefined Upon console.logging siteDa ...

Assistance in using jQuery to locate specific div elements is

I am currently working on creating a navigation bar that features icons triggering contextual submenus upon hover. The main idea is that hovering over an icon will display a popup menu or tooltip with additional options, while still allowing the icon itsel ...

How about connecting functions in JavaScript?

I'm looking to create a custom function that will add an item to my localStorage object. For example: alert(localStorage.getItem('names').addItem('Bill').getItem('names')); The initial method is getItem, which retrieves ...

Aligning a rotated paragraph in the middle of its parent container

Here is my current progress: http://jsfiddle.net/2Zrx7/2/ .events{ height:100px; position: relative; } .tt_username{ position: absolute; top:0px; height: 100%; width: 30px; background: #ccc; text-align: center; } .tt_usern ...

Vue allows you to easily generate child div elements within a parent

Having some issues creating a child div with Vue. The code is being placed correctly, but it's being stored as an array. <template> <div class="containers" v-bind:style="{ backgroundColor: pageStyle.backgroundColor, paddingLeft:'5%& ...

Issue with Component: Data is not being injected into controller from ui-router resolve, resulting in undefined data

Encountering an issue with resolve when using a component and ui-router: the data returned after resolving the promise is displaying as "undefined" in the controller. Service: class userService { constructor ($http, ConfigService, authService) { th ...

Exploring the magic of VueJS: Implementing computed properties for "set/get" functionalities in tandem with Vue.Draggable and

Currently, I am in need of assistance with utilizing "Vue.Draggable". For the past two days, I have been struggling to properly update the draggable array. The main challenge lies in: Updating the draggable array using computed set/get functions Obtaini ...

The JavaScript function's if and else statements are being executed simultaneously

Upon loading the page, I am checking the value of a dropdown. Strangely, when I debug, it appears that the controller is executing both the if and else statements, which should not be happening. /* Here is my code: */ $(window).load(function() { ...

Strategies for handling incorrect input in a dynamic Angular form

I am facing an issue with my dynamic form where I am unable to solve the input errors. The input name is generated dynamically, but I am struggling to access it in the error span. I suspect that the Angular double curly brackets might be rendering slower t ...