1
votes

I'm using AngularJs 1.4.8 and I noticed strange behaviour :

When you have 2 directives one inside of other :

angular.module('another-module', [])
            .directive('anotherModuleOuter', function () {
                return {
                    scope: {},
                    controller: function () {
                        console.log('another-module-outer - controller');
                    },
                    link: function () {
                        console.log('another-module-outer - link');
                    },
                    template: '<div>another-module-outer <div another-module-inner></div></div>'
                }
            })
            .directive('anotherModuleInner', function () {
                return {
                    scope: {},
                    controller: function () {
                        console.log('another-module-inner - controller');
                    },
                    link: function () {
                        console.log('another-module-inner - link');
                    },
                    template: '<div>another-module-inner</div>'
                }
            });

You'd get

another-module-outer - controller
another-module-inner - controller
another-module-inner - link
another-module-outer - link

Meaning that outer directive's controller will be called first and link function - last.

However, if you change inner's template :

template: '<div>another-module-inner</div>'

to templateUrl like :

templateUrl: 'anotherModuleInner.html'

loading order would also change (outer directive's link will be triggered before inner's controller):

another-module-outer - controller
another-module-outer - link
another-module-inner - controller
another-module-inner - link

Why does it work like this?

P.S/

I'm having a problem with events where inner directive registers $scope.$on() and outer fires $rootScope.$broadcast() but since inner function $on is registered after broadcast it doesn't catch anything. I'd be grateful if you suggest a solution.

1

1 Answers

2
votes

The answer you are looking for is in the docs under $compile for templateUrl

Because template loading is asynchronous the compiler will suspend compilation of directives on that element for later when the template has been resolved. In the meantime it will continue to compile and link sibling and parent elements as though this element had not contained any directives.