Mastering Web Application

(Rick Simeone) #1

Building Advanced Directives


This is very useful if you want to make copies of the original element's
children, as it would happen in ng-repeat.

Accessing transclusion functions in directives


The compiler passes this transclusion function back to the directive. There are two
places where you can get hold a transclusion function: the compile function and the
directive controller. There is a section describing directive controllers in detail later
in this chapter.


myModule.directive('myDirective', function() {
return {
transclude: true,
compile: function(element, attrs, transcludeFn) { ... };
controller: function($scope, $transclude) { ... },
};
});

Here we have indicated that the directive should transclude its contents. We can
access the transclusion functions in the compile function, via the transcludeFn
parameter and in the directive controller, via the $transclude parameter.


Getting the transclusion function in the compile function with transcludeFn

The transclusion function is made available as the third parameter of the compile
function of a directive. At this stage of the compilation, the scope is not known so the
transclusion function is not bound to any scope. Instead, you will pass in the scope
to this function, as its first parameter, when you call it.


The scope is available in the linking function and so this is where you will generally
find the transclusion function being invoked.


compile: function(element, attrs, transcludeFn) {
return function postLink(scope, element, attrs, controller) {
var newScope = scope.$parent.$new();
element.find('p').first().append(transcludeFn(newScope));
};
}
Free download pdf