Example: https://ng-teleport.herokuapp.com/
All in all, ngTeleport
has similar functionality to ngTransclude
, but ngTeleport
allows you to uproot a piece of the DOM and place it elsewhere. However, ngTeleport
is entirely Angular.js aware and therefore sets up the scope and interpolation for you.
Note: Using ngTeleport
to move elements around the DOM for responsiveness is no longer recommended – use Flexbox instead. For cases where you require the same functionality for non-supported browsers explain to your CTO that complicating the codebase's architecture to support a handful of antiquated browsers is absurd.
First of all you need to define the ng-teleport
attribute with a unique identifier for the scope on any DOM element you wish to teleport – this allows ngTeleport
to take a note of the precompiled HTML. Once you've defined the ng-teleport
you're free to move it around wherever you wish. Simply add teleport
to your directive, and invoke it with the source
(DOM node with the ng-teleport
attribute), target
, and any additional options.
<section ng-teleport="myElement">
</section>
With the above code section
is now all ready to be teleported anywhere in the DOM where there is a valid Angular scope.
teleport(sectionElement, someOtherNode);
When using ngTeleport
it's crucial that you don't over-complicate your code. Remember that there might always be a better solution for doing what you want to do.
One prominent use case that ngTeleport
is in a responsive design – upon changing the browser window, you may want to shuffle the DOM elements around based on media queries, which is precisely what ngTeleport
allows you to do in an Angular environment.
Option | Type | Default | Result |
---|---|---|---|
duplicate |
Boolean |
false |
Instead of removing the source DOM it instead creates a copy of it. |
retainScope |
Boolean |
false |
Retain the original scope of the node even though it's a child of another scope – not recommended due to complexity). |
insertion |
String |
append |
Can either be append or prepend depending on what you're looking for. |