检测AngularJS指令中是否使用了可选的转置元素?
我有一个如下所示风格的指令设置;它允许可选的转置元素,如示例中使用的检测AngularJS指令中是否使用了可选的转置元素?,angularjs,angularjs-directive,angularjs-ng-transclude,Angularjs,Angularjs Directive,Angularjs Ng Transclude,我有一个如下所示风格的指令设置;它允许可选的转置元素,如示例中使用的和 指令.js(部分) template.html <div ng-transclude="header"> <!-- Transcluded header will appear here --> </div> <div class="static-content"> Lorem ipsum dolor sit amet, consectetur adipiscin
和
指令.js(部分)
template.html
<div ng-transclude="header">
<!-- Transcluded header will appear here -->
</div>
<div class="static-content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</div>
<div ng-transclude="footer">
<!-- Transcluded footer will appear here -->
</div>
我不太清楚克隆是如何工作的,但它似乎是一个节点列表,代表了被排除的内容。不幸的是,我从中得到的唯一有用的信息是长度clone.length
对于我上面的使用示例是3(一个用于dir
,页眉
,和页脚
)。如果我删除footer
,长度将为2,依此类推。但是,似乎没有任何数据来区分节点列表中的元素,因此我无法判断使用了哪些被转置的元素,只是使用了多少
最后,我想根据是否正在使用某个特定的transclude元素来设置一些样式条件。
transclude
函数上的isSlotFilled函数将为您提供所需的结果
angular.module('App', [])
.directive('dir', function () {
return {
restrict: 'E',
template: `
<div ng-transclude="header"></div>
<div class="static-content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</div>
<div ng-transclude="footer">
`,
transclude: {
'header': '?dirHeader',
'footer': '?dirFooter'
},
link: function ($s, $el, $attrs, thisCtrl, $transclude) {
console.log($transclude.isSlotFilled('header'))
console.log($transclude.isSlotFilled('footer'))
}
};
});
angular.module('App',[])
.directive('dir',函数(){
返回{
限制:'E',
模板:`
Lorem ipsum dolor sit amet,是一位杰出的献身者。
`,
排除:{
'header':'?dirHeader',
'页脚':'?页脚'
},
链接:函数($s,$el,$attrs,thisCtrl,$transclude){
log($transclude.isSlotFilled('header'))
console.log($transclude.isSlotFilled('footer'))
}
};
});
工作您使用的是哪个版本的angularjs?默认情况下,angular 1.5.x+@PigBall应该可以工作。我不知道您指的是什么“It”,该指令工作正常。谢谢!不知道为什么我不想检查transclude函数还能做什么。
<dir>
<dir-header>My Header</dir-header>
<dir-footer>My Footer</dir-footer>
</dir>
link: function (scope, elem, attrs, $transclude) {
$transclude(function (clone) {
console.log(clone);
});
}
angular.module('App', [])
.directive('dir', function () {
return {
restrict: 'E',
template: `
<div ng-transclude="header"></div>
<div class="static-content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</div>
<div ng-transclude="footer">
`,
transclude: {
'header': '?dirHeader',
'footer': '?dirFooter'
},
link: function ($s, $el, $attrs, thisCtrl, $transclude) {
console.log($transclude.isSlotFilled('header'))
console.log($transclude.isSlotFilled('footer'))
}
};
});