Note that there are some explanatory texts on larger screens.

plurals
  1. POAdd directives from directive in AngularJS
    primarykey
    data
    text
    <p>I'm trying to build a directive that takes care of <strong>adding more directives</strong> to the element it is declared on. For example, I want to build a directive that takes care of adding <code>datepicker</code>, <code>datepicker-language</code> and <code>ng-required="true"</code>.</p> <p>If I try to add those attributes and then use <code>$compile</code> I obviously generate an infinite loop, so I am checking if I have already added the needed attributes:</p> <pre><code>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); } }; }); </code></pre> <p>Of course, if I don't <code>$compile</code> the element, the attributes will be set but the directive won't be bootstrapped.</p> <p>Is this approach correct or am I doing it wrong? Is there a better way to achieve the same behavior?</p> <p><strong>UDPATE</strong>: given the fact that <code>$compile</code> 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 <code>terminal:true</code>?</p> <p><strong>UPDATE 2</strong>: I have tried putting the directive into a <code>select</code> element and, as expected, the compilation runs twice, which means there is twice the number of expected <code>option</code>s.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload