Add directives from directive in AngularJS

I’m trying to build a directive that takes care of adding more directives to the element it is declared on.
For example, I want to build a directive that takes care of adding datepicker, datepicker-language and ng-required="true".

If I try to add those attributes and then use $compile I obviously generate an infinite loop, so I am checking if I have already added the needed attributes:

angular.module('app')
  .directive('superDirective', function ($compile, $injector) {
    return {
      restrict: 'A',
      replace: true,
      link: function compile(scope, element, attrs) {
        if (element.attr('datepicker')) { // check
          return;
        }
        element.attr('datepicker', 'someValue');
        element.attr('datepicker-language', 'en');
        // some more
        $compile(element)(scope);
      }
    };
  });

Of course, if I don’t $compile the element, the attributes will be set but the directive won’t be bootstrapped.

Is this approach correct or am I doing it wrong? Is there a better way to achieve the same behavior?

UDPATE: given the fact that $compile is the only way to achieve this, is there a way to skip the first compilation pass (the element may contain several children)? Maybe by setting terminal:true?

UPDATE 2: I have tried putting the directive into a select element and, as expected, the compilation runs twice, which means there is twice the number of expected options.

7 Answers
7

Leave a Comment