How to get angular directive to include and replace another directive?

I have an AngularJS directive, directiveFoo , created by an attribute:

 <div directiveFoo></div> 

I want my directiveFoo always instantiate another directive, for example. template:

 <div directiveBar="123"></div> 

My question is, can this be done without creating all the lost nodes? I would like to add replace to my directive, but then it resets directiveFoo

Ultimately, I want:

 <div directiveFoo directiveBar="123"></div> 

with two controllers attached.

This is a simplified example. I am trying to prevent:

 <div directiveA> <div directiveB> <div directiveC="123"> <div directiveD></div> </div> </div> </div> 

in cases when I really don't need all the nested DOM nodes

+4
source share
1 answer

but then it resets the directive foo

It does not follow. "The replacement process transfers all attributes / classes from the old element to the new." - policy document

Since attributes are directive-foo , directive-foo should display in the generated HTML.

 app.directive('directiveFoo', function() { return { template: '<div directive-bar="123">bar</div>', replace: true, } }); 

The above directive leads to the following HTML (tested in Chrome):

 <div directive-bar="123" directive-foo>bar</div> 

Fiddle

In the script, I also create a controller for each directive (since you mentioned that you want it), and I show that directive-bar can access the directive-foo controller.

(I put bar as the text in the template to make it easier to right-click and select "Inspect Element").

+3
source

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


All Articles