AngularJS – Dynamic Directives

In diesem Artikel:

Pawel Gerr ist Architekt und Consultant bei Thinktecture. Er hat sich auf .NET Core Backends spezialisiert und kennt Entity Framework von vorne bis hinten.

In this post, we will look into an approach for exchanging the definition of an AngularJS directive, i.e. the template, controller, compile/link functions etc., after the application has been bootstrapped whereby carrying out a full reload is not an option.

Assume that you have an application that allows the user to have multiple accounts to switch between. Depending on the currently active account, the application establishes a connection to different servers that in turn have different definitions for the same AngularJS directive.

Here is a simplified example:

<my-directive message="'Hello World'" />


	<div>Coming from the Server A</div>


	<span>And now from Server B: Hello World</span>

To be able to exchange the entire definition of an AngularJS directive after the application has started we need to address the following problems:

  • Lazy loading
  • Directive definition exchange
  • On-demand recompilation

Let’s have a look at each point in more detail now.

1) Lazy loading

Problem: The usual way to register a directive does not work after the application has bootstrapped.

					// the usual way to register a directive
angular.module('app').directive('myDirective', MyDirective);


For the registration of an AngularJS directive after the application has started, we need the $compileProvider. We can get a hold of the $compileProvider during the configuration phase, and save the reference somewhere we get access to later, like in a service (in our example it will be the dynamicDirectiveManager).

					// grab the $compileProvider
	.config(function ($compileProvider, dynamicDirectiveManagerProvider) {

// Later on, we are able to register new directives using the $compileProvider
$compileProvider.directive.apply(null, [name, constructor]);


By using the $compileProvider we are now able to lazy-load directives.

2) Directive definition exchange

Problem: Re-registering a directive using the same name but different definition (i.e. template, controller, etc.) does not work.

	.apply(null, [ 'myDirective', function() { return { template: 'Template A', … } } ]);

// … some time later …
	.apply(null, [ 'myDirective', function() { return { template: 'Other template', … } } ]); 
// the previous statement won’t overwrite the directive

Due to caching in AngularJS, the directives that we are trying to overwrite are not going to be exchanged by a new one. To remedy this problem, we have no other choice but to change the name in some way, for example by appending a suffix. Luckily, we can hide this renaming in the previously mentioned dynamicDirectiveManager.

					// will compile to <my-directive-optionalsuffix>
dynamicDirectiveManager.registerDirective('myDirective', function() { return { template: 'Template', … } }, 'optionalsuffix');

// … some time later …
// will compile to <my-directive-randomsuffix>
dynamicDirectiveManager.registerDirective('myDirective', function() { return { template: 'Other template', … } });

3) On-demand recompilation

Problem: Now, we are able to exchange a directive definition by a new one but the corresponding directives on our HTML page will not recompile themselves, especially if the directives (except for markup in the page) did not exist at all a moment ago.

To be able to recompile the directives on demand, the desired directive will be created by another one (say ) that we have full control over. That way we can call $compile() every time a directive has been overwritten.


<dynamic-directive element-name="my-directive" message="'Hello World'"></dynamic-directive>

<dynamic-directive element-name="{{getDirectiveName()}}" message="'Hello World'"></dynamic-directive>

<dynamic-directive element-name="my-directive" message="'Hello World'">
	<my-directive message="'Hello World'" />

<dynamic-directive element-name="my-directive" message="'Hello World'">
	<my-directive-someprefix message="'Hello World'" />


By using the $compile service, we solved one problem but created a memory leak. If the inner directive () requests an isolated or child scope, then we get a deserted scope on each recompile thereby slowing the whole application bit by bit.

To solve this issue, we need to check whether the scope of the inner directive is different than the scope of the . If so, then the inner scope will be disposed of by calling $destroy().

					var innerScope = currentInnerElement.isolateScope() || currentInnerElement.scope();

if (innerScope && (innerScope !== scope)) {



This is a quite special case and it requires quite some code just to overwrite a directive without restarting the application. Luckily, the bulk of the work is done either by the or by dynamicDirectiveManager.

Live working example


Aktuelle Artikel, Screencasts, Webinare und Interviews unserer Experten für Sie

Verpassen Sie keine Inhalte zu Angular, .NET Core, Blazor, Azure und Kubernetes und melden Sie sich zu unserem kostenlosen monatlichen Dev-Newsletter an.

Newsletter Anmeldung
Diese Artikel könnten Sie interessieren

View Transition API Integration in Angular—a brave new world (Part 1)

If you previously wanted to integrate view transitions into your Angular application, this was only possible in a very cumbersome way that needed a lot of detailed knowledge about Angular internals. Now, Angular 17 introduced a feature to integrate the View Transition API with the router. In this two-part series, we will look at how to leverage the feature for route transitions and how we could use it for single-page animations.
Low-angle photography of metal structure

AI-Funktionen zu Angular-Apps hinzufügen: lokal und offlinefähig

Künstliche Intelligenz (KI) ist spätestens seit der Veröffentlichung von ChatGPT in aller Munde. Wit WebLLM können Sie einen KI-Chatbot in Ihre eigenen Angular-Anwendungen integrieren. Wie das funktioniert und welche Vor- und Nachteile WebLLM hat, lesen Sie hier.

Konfiguration von Lazy Loaded Angular Modulen

Die Konfigurierbarkeit unserer Angular-Module ist für den Aufbau einer wiederverwendbaren Architektur unerlässlich. Aber in der jüngsten Vergangenheit hat uns Angular seine neue modullose Zukunft präsentiert. Wie sieht das Ganze jetzt aus? Wie konfigurieren wir jetzt unsere Lazy-Komponenten? Lasst uns gemeinsam einen Blick darauf werfen.

Using EntityAdapter with ComponentStore: @ngrx/entity Series – Part 3

As someone who enjoys the ComponentStore on an average level, I have written simple reactive CRUD logic several times. While storing a vast number of entities in the component state might not be a frequent use case, I will briefly illustrate the usage of the EntityAdapter with the @ngrx/component-store.

Multiple Entity Collections in the Same Feature State: @ngrx/entity-Series – Part 2

After introducing the @ngrx/entity package, I am often asked how to manage multiple entity types in the same feature state. While I hope that the previous part of this article series has made this more apparent, I will further focus on this question in the following.

Managing Your Collections With the EntityAdapter: @ngrx/entity-Series – Part 1

This three-part series of blogposts is targeted at developers who have already gained experience with NgRx but still manage their collections themselves. In the first part I introduce the Entity Adapter, in the second part I show you how to connect it to NgRx and in the third part how to do it with the Component Store as well.