Transclusion Basics

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 11 years ago
Updated 6 years ago

Uh oh. Transclusion? What the heck? It's a big word, but it is actually a very simple concept. In this episode John shows you how transclusion is used in your AngularJS directives...

John Lindquist: So what happens when you have a customer directive, its component, say, call it "panel" and then you put something like a "button" inside of your customer component. You haven't defined it yet, but your button look like that.

Once we define our directive, if it's a directive that we give a template, we call this panel return and strict to element. Then, you've got a template of "div" with a class of panel and this is a panel component..."Grey component."

If we are refreshing here, you can see that it has rendered out our template, yet our button that we defined in here, is completely disappeared because the template has pretty much overwritten and destroyed the content that was in there.

If you want that content to be carried over from the "DOM" into your "directive," what you need to do is set up something called "Transclusion." It's a very funky name for actually a pretty simple concept. You say "transclude true," I like to say it's going to yank this and basically, copy and paste it into wherever you design "NG Transclude."

If you say NG transclude on this element, it's going to append it into that div. It's taking it from the inside of where we defined it, basically, copied and pasted and dropped it into our component because we set transclude there and then added transclude to our element.

This is a pretty common scenario, as far as making your html markup very descriptive and declarative of what is going on. You probably run into this scenario quite a bit, and it's really easy to use.

There are some pretty advance cases around transclusion...That we will get into, like compiling phase and things like that. We will talk more about that as we get into our advance stuff. But for right now, this is pretty simple, so go ahead and start using it.

yiling
yiling
~ 10 years ago

In Angular 1.3.15, we have two options for the transclusion behaviour quote from angularjs doc:

  • true - transclude the content (i.e. the child nodes) of the directive's element.
  • 'element' - transclude the whole of the directive's element including any directives on this element that defined at a lower priority than this directive. When used, the template property is ignored.
Markdown supported.
Become a member to join the discussionEnroll Today