Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular ng-if like directive

Tags:

angularjs

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

like image 693
jonasnas Avatar asked May 05 '16 09:05

jonasnas


1 Answers

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

like image 77
dfsq Avatar answered Sep 18 '22 12:09

dfsq