Chapter 9
When a directive requests transclusion, AngularJS will extract the transcluded
elements from the DOM and compile them. Here is an approximation of what
happens with transclude: true:
var elementsToTransclude = directiveElement.contents();
directiveElement.html('');
var transcludeFunction = $compile(elementsToTransclude);
The first line gets the contents of the element containing the directive that requested
the transclusion. The second line clears this element. The third line compiles the
transcluded contents to produce the transclusion function, which will be passed
back to the directive, for it to use.
Creating a transclusion function with the $compile service
The AngularJS compiler is exposed as the $compile service. This is the same function
that is used when compiling any other part of an AngularJS application. To use this
service we simply call it with a list of DOM nodes (or a string that will be parsed into a
list of DOM nodes).
var linkingFn = $compile(
'<div some-directive>Some {{"interpola-ted"}} values</div>');
The call to $compile service returns a linking function. You call this function with a
scope to retrieve a DOM element containing the compiled DOM elements, bound to
the given scope:
var compiledElement = linkingFn(someScope);
Transclusion functions are just special instances of link functions.
Cloning the original elements when transcluding
If we pass in a call-back function as a parameter to a linking function then a clone of
the elements will be returned instead of the original elements. The call-back function
will be called synchronously with the cloned elements as a parameter.
var clone = linkingFn(scope, function callback(clone) {
element.append(clone);
});