admin管理员组

文章数量:1208155

In the John Lindquist tutorial, transclusion is used to grab some content from the directive and put it in a desired place.

But the docs talk about translude function and passing it to controller and compile function. So, what is transclusion and how do I use it?

In the John Lindquist tutorial, transclusion is used to grab some content from the directive and put it in a desired place.

But the docs talk about translude function and passing it to controller and compile function. So, what is transclusion and how do I use it?

Share Improve this question asked Jan 24, 2013 at 20:17 user1624400user1624400 3955 silver badges13 bronze badges 1
  • 4 I noticed you still haven't accepted any answer. Did you need more help on this question? – Josh David Miller Commented Feb 1, 2013 at 1:28
Add a comment  | 

3 Answers 3

Reset to default 16

When creating a basic directive, transclusion is easy:

module.directive( 'myTransDir', function () {
  return {
    transclude: true,
    scope: true,
    replace: true,
    template: '<div><h1>Hello!</h1><div ng-transclude></div></div>',
  };
});

Because the template includes the ngTransclude directive, it will automatically transclude the contents for me. If I use it like this:

<div my-trans-dir>
  <p>Some Content</p>
</div>

The resultant HTML will be:

<div>
  <h1>Hello!</h1>
  <div>
    <p>Some Content</p>
  </div>
</div>

@Josh already covered ngTransclude. This is the "normal use case" for transclusion.

You were also asking about these statements in the documentation:

controller - Controller constructor function...
The controller is injectable with the following locals:
...
$transclude - A transclude linking function pre-bound to the correct transclusion scope: function(cloneLinkingFn).

and

The compile function deals with transforming the template DOM...
The compile function takes the following arguments.
...
transclude - A transclude linking function: function(scope, cloneLinkingFn).

I consider these esoteric use cases of transclusion. I've personally only seen one mention of these on stackoverflow, and I'll refer you there:
What exactly do you do with the transclude function and the clone linking function?

Quote from @blesh: "these two methods of transclusion are there to give you the ability to control everything about you transclusion via programmatic access to the process."

Update: I found a nice blog post about transclusion.

Johns "Building Zippy" tutorial on egghead.io is the best description I have seen on transclusion. You are right with both statements, John just gives an example, but whats happening behind the scenes is the html in the markup is put through the compiler with the template. In his tutorial, John leaves content in the template on accident, and you can see how angular's compiler concatenates the markup html and the template html.

本文标签: javascriptHow do I use transclusion in angularjsStack Overflow