I want to have a directive that checks the tag name
of component and based on some condition shows/hides the component. I want showing hiding to behave like ng-if
(not initialising controller of component). Example:
<my-component custom-if></my-component>
Inside the directive custom-if
:
return {
compile: function($element) {
if($element[0].tagName === 'some condition'){
//Element is my-component
$element.remove();
}
}
};
The problem I have is that even if I remove element it still calls controller of the my-component. Same happens if I remove element inside compile
or preLink
function of directive. I also tried to inherit ng-if
but I can't get the tag name of component inside custom-if
directive because the element is a comment
(probably it is ng-if
specific behaviour to wrap element inside comment)
UPDATE: Changed postLink
function to compile
to make sure it doesn't work as well. It shows / hides the element but it always instantiates controller even if it is removed and that's what I want to avoid
I think you should be able to do it by making customIf
hight priority directive. Then in compile function, you can check if host component/directive is allowed to continue or not. If not, customIf
just removes element altogether. If check passes, then customIf
needs to remove itself by unsetting own attribute and then recompile element again.
Something like this:
.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);
}
}
}
};
});
Demo: http://plnkr.co/edit/Y64i7K4vKCF1z3md6LES?p=preview
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With