Custom transclusion with Angular

Updated . Posted . Visible to the public.

Angular's directives have a transclude option, that allows for rendering an element's original content within the directive's template:

# HTML
<wrapping-directive>
  Content ...
</wrapping-directive>
# Directive template
<div class="wrapper">
  <ng-transclude></ng-transclude>
</div>
# Result
<div class="wrapper">
  Content ...
</div>

However, if you need more control over the transcludable content you need heavier armor. For this case, Angular provides you with a transclusion function as the 5th argument of the link function.

Transclusion function

You can use the transclude function to process the transcluded content before adding it to the DOM.

# Directive
template:
  """
  <div class="wrapper">
  </div>
  """
transclude: true
link: (scope, element, attributes, _controller, transclude) ->

  transclude (content) ->
    # Do custom stuff
    element.find('.wrapper').append(content)

There is actually much more you can do with the transclusion function. For an in-depth introduction, see this Guide to Angular Transclusion Show archive.org snapshot . Also read the Angular docs Show archive.org snapshot on this.

Dominik Schöler
Last edit
Besprechungs-PC
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2016-02-12 16:01)