Angular: creating a template with a directive inside another directive

Let me share a simple example...

Here is the code snippet:

angular
      .module('app', [])
      .directive('parentDirective', parentDirective)
      .directive('childDirective', childDirective);

    function parentDirective() {
      return {
        restrict: 'E',
        scope: true,
        //template: 'My job is {{job}}', 
        controller: function($scope) {
          $scope.job = 'gardener';
          $scope.say = function(job) {
            $scope.job = job;
            alert($scope.job);
          }
        }
      };
    }

    function childDirective() {
      return {
        restrict: 'E',
        link: function(scope) {
          scope.say('landscaper');
        }
      };
    }

The Markup is as follows:

    <parent-directive>
        <child-directive></child-directive>
    </parent-directive>

The functionality works perfectly. However, I am facing an issue when trying to add a template to the parentDirective while achieving the same result. Upon uncommenting the template property, the binding remains unchanged and the alert is not triggered anymore. Can anyone provide a brief explanation of what is happening in this scenario? Maybe even assist in enhancing my example? I find that learning through examples is most effective :)

Answer №1

To automatically render a template property within a parent directive using a child directive, the following approach can be taken:

For instance:

angular .module('app', []) .directive('parentDirective', parentDirective) .directive('childDirective', childDirective);

function parentDirective() {
  return {
    restrict: 'E',
    scope: true,
    template: '<div>{{job}} is seen<child-directive></child-directive></div>'
    //template: 'My job is {{job}}', 
    controller: function($scope) {
      $scope.job = 'trashman';
      $scope.say = function(job) {
        $scope.job = job;
        alert($scope.job);
      }
    }
  };
}

function childDirective() {
  return {
    restrict: 'E',
    template: '<div>I will be renderred</div>',
    link: function(scope) {
      scope.say('shoe shine boy');
    }
  };
}

By utilizing the parent directive with the child directive nested inside it, the child directive's html content will also be rendered.

For example:

<parent-directive></parent-directive>

With this setup, Angular will recognize the parent directive, render it, and further include the child directive's content within the parent element for rendering.

Answer №2

When utilizing the directive template, it will substitute the directives inner content with the template causing the inner directive to potentially not be rendered.

To ensure that the child directive HTML is included in the parent directive template, you must incorporate ng-transclude in the parent template. In your directive definition object, specify

transclude: true,

and

template: '<div> My job is {{job}} <ng-transclude></ng-transclude></div>'

This information can be found in the $compile documentation

Replace the contents of the directive's element (default).

Replace the directive's element itself (if replace is true - DEPRECATED).

Wrap the contents of the directive's element (if transclude is true).

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

Dynamically load scripts in angularJs

Having multiple libraries and dependencies in my angularjs application is posing a challenge as I want to load them all using just one script, given that three apps are utilizing these dependencies. Currently, I have this custom script: var initDependenci ...

The random number generator in TypeScript not functioning as expected

I have a simple question that I can't seem to find the answer to because I struggle with math. I have a formula for generating a random number. numRandomed: any; constructor(public navCtrl: NavController, public navParams: NavParams) { } p ...

Using AngularJS $http.get method returns JSON with numeric keys, but we actually do not want any keys

Currently, I am conducting local testing on an AngularJS website. The issue I am facing involves parsing JSON data using the $http.get method from a local JSON file. When I manually define the JSON within my controller, everything works smoothly. However, ...

Improving HTML coding with a more effective alternative to document.write()

Looking at the setup of my website, I have a menu button and comments section that need to appear on every page. Instead of manually adding this code to each HTML file, I decided to streamline the process by using a JavaScript file that generates all of th ...

What is the best way to find the average time in Typescript?

I am dealing with an object that contains the following properties: numberOfReturns: number = 0; returns_explanations: string [] = []; departure_time: string = ''; arrival_time: string = ''; The departure_time property hold ...

Exploring Objects and JSON in React Next.JS: Delving Inside the Object ID

Here is the JSON data I am working with: { "quoteId":"7ab6cb9f-f1a9-4484-aee7-686ba6f7e7a8", "groups":{ "group1":{ "pickup":{ }, "pickupExceptions":[ ], "shipment":{ ...

Polymorph 1.0 - Using CSS Class Binding for Dynamic Properties

I attempted to link a CSS Class to a paper-progress element using the value of my property to change the item's color. I referenced Polymer's example on GitHub and studied the documentation on Data-binding. Here is my code: http://jsbin.com/bide ...

Confirm the email during registration with Node.js and Express.js

Hello, I am just starting out with the MeanJS framework (MongoDB, ExpressJS, NodeJS, and AngularJS) and I could really use some guidance on how to send an email with a verification link for new users. Can you please help me understand this process? ...

Creating an inverted curve or border-radius for a div element is a design technique that can add

I've been tackling a project that requires me to style the border of a div in an inverted manner. To achieve this, I'm limited to using only CSS and JS without any plugins. I've searched through various online resources and similar questions ...

Add a dynamic navigation class based on the current URL for corresponding URLs

Looking for a way to dynamically add an active class to navigation links? I came across this helpful article: Add Active Navigation Class Based on URL $(function(){ var current = location.pathname; $('#nav li a').each(function(){ ...

Unraveling the Mystery Behind Zero Array Problems

DESCRIPTION: A collection of elements is classified as zero-plentifull if it contains multiple occurrences of zeros, and each sequence of zeros consists of at least 4 items. The objective is to determine the number of zero sequences in the array if it mee ...

Implementing dotenv in a Node JS package

I'm in the process of developing a Node application that retrieves search results through a Google Custom Search Engine (CSE). To streamline the process, I plan to extract the component responsible for sending requests to Google and receiving the res ...

What is the exact functioning of the Array.push() method in Javascript?

During my online CS class, we covered the topic of how Arrays and memory work. The teacher used C as an example to explain that you cannot add extra elements to a full Array. As someone who started with JavaScript, I found it interesting that in JavaScript ...

construct a table utilizing JSON information

If I have data returned from an ajax call that needs to be processed, a table like the following needs to be created: ID NAME Object Type ============================================== 1 SWT-F1-S32-RTR-1 Network Switch 2 ...

Tips for managing state updates in React Redux

Currently, I am utilizing a reducer to manage the state in Redux. The current structure of my state is as follows: { activeConversation: "Jim" conversations: (7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}] user: {id: 8, username: &quo ...

Error: Trying to access the 'previous' property of an undefined value

I keep encountering an error with functions in firebase: TypeError: Cannot read property 'previous' of undefined at exports.sendNotifications.functions.database.ref.onWrite (/srv/index.js:5:19) at cloudFunction (/srv/node_modules/firebase-functi ...

Regular expression pattern for consistently capitalizing the phrases "CA" and "USA" in an address string

end_address = 'joe's home, 123 test avenue, los angeles, ca, usa 90210'; end_address = end_address.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}); The outcome of this code will ...

Generate a custom Elementor shortcode dynamically using JavaScript

I have a custom-built website using WordPress and Elementor. I am running code through the html element in Elementor to display dropdown menus. When a value is selected from each dropdown and the button is clicked, the values are stored in variables and th ...

What is the proper way to define the types for the lodash flow function in TypeScript?

lodash.flow is a powerful function that can combine two or more functions to create a new function. For example, using lodash.flow(double, addTwo) would result in a function that doubles a number and then adds two to it. However, when working with TypeScr ...

Database storage of image tags on websites, similar to functionality found on social media platforms such as Facebook

Looking for an image tagging solution for websites that can save tag data directly to a database instead of a local file? I've checked out , but it doesn't support database integration in the current version. Ideally, I need a solution that is co ...