This question explores how to create a wrapper AngularJS directive that adds additional directives to the element it is applied to. The goal is to avoid an infinite loop when attempting to add and then compile the new directives using $compile.
The provided solution employs the following steps:
Priority and Terminal Settings:
Directive Compilation:
<code class="javascript">angular.module('app') .directive('commonThings', function ($compile) { return { restrict: 'A', replace: false, terminal: true, priority: 1000, link: function (scope, element, attrs) { element.attr('tooltip', '{{dt()}}'); element.attr('tooltip-placement', 'bottom'); element.removeAttr("common-things"); // Remove the wrapper directive's attribute element.removeAttr("data-common-things"); // Also remove the same attribute with data- prefix $compile(element)(scope); } }; });</code>
This approach provides a robust solution for incorporating multiple directives from a wrapper directive while avoiding the potential for infinite loops. The priority and terminal properties are crucial in achieving the desired behavior, and it is important to remove the wrapper directive's attribute after modifying the element to prevent further compilation.
The above is the detailed content of How to Avoid Infinite Loops When Adding Directives from a Wrapper Directive in AngularJS?. For more information, please follow other related articles on the PHP Chinese website!