简体   繁体   中英

Proper way to nest a directive in angular

Here is my plunkr: http://plnkr.co/edit/A0s3kafWD1WIaFcwimIT?p=preview

I am trying to nest a directive inside another directive but it is not working.

Angular:

app.directive('test', function() {
  return {
    restrict: 'E',
    template: '<div>Hello Parent</div>'
  }
})


app.directive('childtest', function() {
  return {
    restrict: 'E',
    template: '<div>Hello Child</div>'
  }
})

HTML:

<test>
  <childtest>  
  </childtest>
</test>

How do I correctly do this?

I think it very much depends on your actual use-case, but you have some options:

  • Don't give the parent directive a template:

     app.directive('test', function() { return { restrict: 'E' } }); app.directive('childtest', function() { return { restrict: 'E', template: '<div>Hello Child</div>' } }); 

    HTML

     <test> <childtest> </childtest> </test> 
  • Put the children in the template of the parent:

     app.directive('test', function() { return { restrict: 'E', template: '<div>Hello parent <childtest></childtest></div>' } }); app.directive('childtest', function() { return { restrict: 'E', template: '<div>Hello Child</div>' } }); 

    HTML

     <test></test> 
  • Give the parent a template, and use transclusion to move the child directive to inside the template

     app.directive('test', function() { return { restrict: 'E', transclude: true, template: '<div>Hello Parent <div ng-transclude></div></div>' } }); app.directive('childtest', function() { return { restrict: 'E', template: '<div>Hello Child</div>' } }); 

    HTML

     <test> <childtest> </childtest> </test> 

Basically I think what you are looking for here is ng-transclude . What it does is it allows you to keep any child elements inside of your custom directive - all the while still allowing you to add elements either before or after those child elements.

Including this, basically your parent directive changes to:

app.directive('test', function() {
  return {
    restrict: 'E',
    transclude: true,
    template: '<div>Hello Parent<div ng-transclude></div></div>'

  }
});

The <div ng-translcude></div> tells angular exactly where you want the child included at and adding the transclude: true tells angular that you want to have this behavior. Take a look at your updated plunker here: http://plnkr.co/edit/HL9PD6U4V7p56T3Cqx5F?p=preview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM