Multiple Transclusion Before Angular 1.5
The purpose of this article is to showcase an approach for achieving multiple transclusion (aka multi-slot transclusion) in Angular apps versioned before v1.5.
So it looks as though this was possible as far back as Angular 1.2.18 according to the Angular 1.2.18 Changelog. I however, just recently needed this functionality for a custom directive and I decided to share a simplified example demonstrating how it works.
I initially reviewed an approach by Ben Nadel (great go-to Angular guru) via his Creating An Isolate-Scope Directive With Multiple Transclusion Points In AngularJS article, but it seemed too complex. In reviewing the
$compile docs I soon found what I was after.
At the core, a directive's link function signature includes a 5th argument as of v1.2.18:
link(scope, element, attributes, controller, transcludeFn)
transcludeFn is the key. It ultimately allows you to:
- Selectively extract the core transcluded content
- Selectively append each extraction to a target element in the directive's template
Below is a sample directive implementing the functionality we are after. Take note:
- The directive's
trueto inject the initial transcluded content
transcludableis parsed for selective extraction
- Select template nodes attain new content via
transcluder()method links everything together
I just found an article on AirPair that demonstrates the same approach. It provides a
MultiTranscludeService in addition for proper reusability.
If you want to see the above code in action, then check out this minimal CodePen demo.CodePen