AngularJS directive loaded dynamically in ng-include do not work

All we need is an easy explanation of the problem, so here it is.

I have a custom directive which adds some html.

myAppModule.directive('myDirective', function() {
    var linker = function(scope, element) {
        return element.html("<b>directive loaded</b>");
    };
    return {
        restrict: "E",
        rep1ace: true,
        link: linker,
        scope: false
    };
});

This directive is loaded and used in a dynamically loaded html which is included via ng-include.

<script type="text/javascript" src="dynamicscript.js"></script>
<my-directive>...</my-directive>

But it does’t work. The linker-function is never called.
It works if I move the dynamicscript.js script loading from the included html to the index.html.

Here is the Plunkr

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Just use RequireJS to load the controllers, directives, and so on.

Using special plugins, CSS and HTML files can be loaded too.

Here is a great example from Ben Nadel: http://www.bennadel.com/blog/2554-Loading-AngularJS-Components-With-RequireJS-After-Application-Bootstrap.htm

Method 2

All JS files should be included in ‘index.html’
JS files (services, modules, controllers) loaded dynamically using ng-include will not work

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply