When should I use transclude: 'true'
and when transclude: 'element'
?
I cant find anything about transclude: 'element'
in the angular docs, they are pretty confusing.
I would be happy if someone could explain this in simple language. What is the benefit of each option? What is the real difference between them?
This is what I have found :
transclude: true
Inside a compile function, you can manipulate the DOM with the help of transclude linking function or you can insert the transcluded DOM into the template using ngTransclude directive on any HTML tag.
and
transclude: ‘element’
This transcludes the entire element and a transclude linking function is introduced in the compile function. You can not have access to scope here because the scope is not yet created. Compile function creates a link function for the directive which has access to scope and transcludeFn lets you touch the cloned element (which was transcluded) for DOM manipulation or make use of data bound to scope in it. For your information, this is used in ng-repeat and ng-switch.
From AngularJS Documentation on Directives:
transclude: true
So let's say you have a directive called
my-transclude-true
declared withtransclude: true
that looks like this:After compiling and before linking this becomes:
The content (children) of
my-transclude-true
which is<span>{{ something }}</span> {{...
, is transcluded and available to the directive.transclude: 'element'
If you have a directive called
my-transclude-element
declared withtransclude: 'element'
that looks like this:After compiling and before linking this becomes:
Here, the whole element including its children are transcluded and made available to the directive.
What happens after linking?
That's up to your directive to do what it needs to do with the transclude function.
ngRepeat
usestransclude: 'element'
so that it can repeat the whole element and its children when the scope changes. However, if you only need to replace the tag and want to retain it's contents, you can usetransclude: true
with thengTransclude
directive which does this for you.