I have recently come across transclusion in directives, what is the purpose of having this concept. As far as I know its encapsulation of an object and have 2-way binding possibly. But this can be possible by using '=' in the scope attribute in directive. So whats the big deal about directive?
Transclude allows :
- To create directives that wrap other elements.
- To clone the same transcluded contents multiple times.
- To re-clone the trancluded contents when an event occurs.
ngTransclude and $transclude
- When using the transclude option, the element contents are being removed from the DOM during the compile phase.
- The 5th argument of the
linking phase
( or $transclude inside directive controllers ) is a$transclude function
which allows you to clone the transcluded contents , apply it to a scope and reinsert it to the DOM when you need. - Angular.js has a built-in directive for simple cases: ngTransclude
I recommend these tutorials:
Some angular built-in directives (ng module) use the transclude
option:
In the docs
What does transclude option do? it makes the contents of a directive with this option have access to the scope outside of the directive rather than inside.
Actually, that's not so accurate, it applies only to the default behavior of angular.js built-in directives and the default behavior of the $transclude function when invoked without scope argument.
The $transclude function allows you to apply any scope you need as an optional first argument:
app.directive('example',function(){
return {
transclude: true,
template: "<div>example</div>"
link: function (scope, element, attrs, ctrl, $transclude){
$transclude(scope, function(clone){
element.append(clone);
})
}
}
})
My main use is to relocate the inner contents of a directive to wherever the ngTransclude
is inside the template of the directive.
http://plnkr.co/edit/aQ7SG58g0njSerM8FsNz?p=preview
var app = angular.module('myApp', []);
app.directive('wrapMe', [function () {
return {
restrict: 'E',
transclude: true,
template: '<span>Stuff before [<b ng-transclude></b>] Stuff after</span>'
};
}]);
来源:https://stackoverflow.com/questions/21087717/what-is-the-main-use-of-transclusion-in-angularjs