Multiple Transclusion Before Angular 1.5
Article Purpose
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.
Basics
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)
This 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
HTML
Here is a sample of HTML to use as reference when viewing the JavaScript below:
JavaScript
Below is a sample directive implementing the functionality we are after. Take note:
- The directive's
transclude
propererty istrue
to inject the initial transcluded content transcludable
is parsed for selective extraction- Select template nodes attain new content via
append()
- The
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