我希望有一个指令来检查tag name组件,并根据某些条件显示/隐藏组件.我希望显示隐藏行为ng-if(不初始化组件的控制器).例:
<my-component custom-if></my-component>
Run Code Online (Sandbox Code Playgroud)
在指令内custom-if:
return {
compile: function($element) {
if($element[0].tagName === 'some condition'){
//Element is my-component
$element.remove();
}
}
};
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是,即使我删除了元素,它仍然会调用 my-component的控制器.如果我删除内部元素compile或preLink指令函数,也会发生同样的情况 我也尝试继承ng-if但是我无法在custom-if指令中获取组件的标签名称,因为该元素是一个comment(可能是ng-if将元素放在注释中的特定行为)
更新:更改postLink功能以compile确保它不起作用.它显示/隐藏元素,但它总是实例化控制器,即使它被删除,这就是我想要避免的
dfs*_*fsq 10
我认为你应该能够通过制定customIf高优先级指令来做到这一点.然后在编译函数中,您可以检查是否允许主机组件/指令继续.如果没有,customIf只需完全删除元素.如果检查通过,则customIf需要通过取消设置自己的属性来删除自身,然后再次重新编译元素.
像这样的东西:
.directive('customIf', function($compile) {
return {
priority: 1000000,
terminal: true,
compile: function(element, attrs) {
if (element[0].tagName === 'MY-COMPONENT') {
element.remove();
}
else {
// remove customIf directive and recompile
attrs.$set('customIf', null);
return function(scope, element) {
$compile(element)(scope);
}
}
}
};
});
Run Code Online (Sandbox Code Playgroud)
演示: http ://plnkr.co/edit/Y64i7K4vKCF1z3md6LES?p=preview
| 归档时间: |
|
| 查看次数: |
2088 次 |
| 最近记录: |