[英]Proper way to nest a directive in angular
Here is my plunkr: http://plnkr.co/edit/A0s3kafWD1WIaFcwimIT?p=preview 这是我的pl客: 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: 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 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 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 HTML
<test> <childtest> </childtest> </test>
Basically I think what you are looking for here is ng-transclude
. 基本上,我认为您在这里寻找的是
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. <div ng-translcude></div>
准确地告诉angular您要在其中包含子项的位置并添加transclude: true
告诉angular您想要此行为。 Take a look at your updated plunker here: http://plnkr.co/edit/HL9PD6U4V7p56T3Cqx5F?p=preview 在这里查看更新的插件: http ://plnkr.co/edit/HL9PD6U4V7p56T3Cqx5F?p=preview
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.