Angular.js: using a directive, insert another directive as an attribute

For example, UI Bootstrap has a directive called 'typeahead' that offers values ​​for a field. Let's say I want to make a directive that I can use as an attribute for an element that will call colors for this element.

Here's an attempt that fails ...

Directive

angular.module('myApp') .directive('suggestcolors', function () { return { compile: function compile(element, attrs) { attrs.$set("typeahead", "color for color in ['red', 'blue', 'green']"); } }; }); 

View:

 <textarea ng-model="foo" suggestcolors></textarea> 

When I check the text box, the attribute has been set, but it does nothing. The same thing happens if I translate the change from attrs to a communication function. Setting the typeahead attribute directly in the view works as expected:

 <textarea ng-model="foo" typeahead="color for color in ['red', 'blue', 'green']"></textarea> 

(But I want to be able to insert this attribute dynamically for DRY reasons. My actual use case is more complicated.)

A similar question was asked here (about dynamically adding ng-click behavior at compile time), but he never answered directly.

+4
source share
1 answer

After compilation, AngularJS only calls $compile for all children. The element itself does not automatically recompile, so adding a directive at this stage will have no effect. In your case, I think you can change it from a compilation function to a communication function (so that you get the scope argument) and call $compile(element)(scope) yourself.

See Fiddle , where I have a directive that adds style="color: red" , and another directive that "dynamically" adds this directive. It does not work unless I call $compile after that.

NTN!

+6
source

Source: https://habr.com/ru/post/1497169/


All Articles