Software Engineering

Nov 3, 2016

3 min


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.


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:

  1. Selectively extract the core transcluded content
  2. Selectively append each extraction to a target element in the directive's template


Here is a sample of HTML to use as reference when viewing the JavaScript below:


Below is a sample directive implementing the functionality we are after. Take note:

  1. The directive's transclude propererty is true to inject the initial transcluded content
  2. transcludable is parsed for selective extraction
  3. Select template nodes attain new content via append()
  4. 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.