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:

<!-- the user is not logged in => show nothing (or some default content) -->
<my-directive message="'Hello World'" />


<!-- the user is connected to “server A” => fetch and apply the directive definition delivered by “server A” 
	restrict: 'E',
	template: '<div>Coming from Server A</div>'
	<div>Coming from the Server A</div>


<!-- the user is connected to “server B” => fetch and apply the directive delivered by “server B”
	restrict: 'E',
	scope: {
		message: '='
	template: '<span>And now from Server B: {{message}}</span>'
	<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.

<!-- Remark: the attribute “message” has no meaning for the <dynamic-directive> but for <my-directive> -->

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

<!-- … will initially compile into something like … -->
<dynamic-directive element-name="my-directive" message="'Hello World'">
	<my-directive message="'Hello World'" />

<!-- … and after a registration of a new directive definition … -->
<dynamic-directive element-name="my-directive" message="'Hello World'">
	<my-directive-someprefix message="'Hello World'" />

<!-- from now on, the <my-directive> is on its own, at least until the next exchange of the directive definition … -->

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

Related Articles

entity framework core
Is "N+1 Queries" still a performance issue in Entity Framework Core 3?
In a previous post we saw that EF 2.1 is highly susceptible to the N+1 queries problem. After the release of a new version of Entity Framework Core (EF) the first question coming to mind is: "Is it still a big issue in EF 3.1?" And if the answer is no, is there anything else we…
Pawel Gerr
Electron Cross-Plattform Desktop Apps - Teil 1: Basics, Architektur, Demo, Vergleich [Screencast]
Thinktecture Cloud-Native und Infrastructure as Code Spezialist Thorsten Hans erklärt in einer vierteiligen Serie das von GitHub ins Leben gerufene Framework Electron. Der erste Teil führt kurz in die Entstehung ein, die Gründe es zu verwenden, erklärt die Architektur und stellt…
Thorsten Hans
Integrating BabylonJS 3D engine into an Angular business application - Part 2 - Performance optimization
Welcome to the second part of this blog post series. If you want to learn how to basically integrate BabylonJS into Angular (or vice versa) please take a look at part 1. In this post, our goal is to make your application and the interactions fast! What to expect in part 2 A…
Max Schulte
Advanced Progressive Web Apps - Push notifications under control - Part 1: Notifications API
For sure, Progressive Web Apps (PWA) are one of the hottest topics on the web today. A PWA should feel like a real app, including the ability to show push notifications. In this blog series, you will learn how to implement push messaging in your PWA or website using the Push API…
Christian Liebel