[英]Proper way to nest a directive in angular
这是我的pl客: http ://plnkr.co/edit/A0s3kafWD1WIaFcwimIT?p=preview
我试图将一个指令嵌套在另一个指令中,但是它不起作用。
角度:
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>
如何正确执行此操作?
我认为这很大程度上取决于您的实际用例,但是您可以选择以下几种方式:
不要给父指令一个模板:
app.directive('test', function() { return { restrict: 'E' } }); app.directive('childtest', function() { return { restrict: 'E', template: '<div>Hello Child</div>' } });
HTML
<test> <childtest> </childtest> </test>
将孩子放在父模板中:
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>
给父级一个模板,并使用包含将子级指令移动到模板内部
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>
基本上,我认为您在这里寻找的是ng-transclude
。 它的作用是允许您将任何子元素保留在自定义指令中-始终允许您在这些子元素之前或之后添加元素。
包括这一点,基本上您的父指令更改为:
app.directive('test', function() {
return {
restrict: 'E',
transclude: true,
template: '<div>Hello Parent<div ng-transclude></div></div>'
}
});
<div ng-translcude></div>
准确地告诉angular您要在其中包含子项的位置并添加transclude: true
告诉angular您想要此行为。 在这里查看更新的插件: http ://plnkr.co/edit/HL9PD6U4V7p56T3Cqx5F?p=preview
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.