In my solution, I had a few custom directives that needed to be loaded first because they contained the definition of functions that their sibling directives call. For example:
<div id="container">
<custom-directive1></custom-directive1>
<custom-directive2></custom-directive2>
<custom-directive3></custom-directive3>
</div>
Unfortunately, none of the solutions on here worked for me, because they only worked after rendering a directive, not the directive code behind.
So when I implemented any of the solutions above, to execute some load function, even though the directive were rendered, the scope didn't know what the functions inside those directives were.
So I created an observable anywhere in my controller:
//Call every time a directive is loaded
$scope.$watch('directiveLoaded', function (value) {
debugger;
if (value == document.querySelector('#container').children.length) {
//Its ok to use childHead as we have only one child scope
$scope.$$childHead.function1_Of_Directive1();
$scope.$$childHead.function1_Of_Directive2();
}
});
Then I have these two directives, where I place
scope.$parent.directiveLoaded += 1;
at the bottom of every directive. Because in the controller I have the observable defined, each time I update the variable directiveLoaded
, it executes the observable function. Yes, I know this is a hack, but it's a small price to pay to guarantee all directives finish the rendering along with their code behind before executing the final function.
To complete the demo here are two directives that define the functions that need to be called later.
Directive1
(function () {
app.directive('customDirective1', function () {
return {
restrict: 'E',
templateUrl: '/directive1.html',
link: function (scope) {
scope.function1_Of_Directive1 = function() {
scope.function2_Of_Directive2();
console.log("F1_D1")
}
//AT BOTTOM OF EVERY DIRECTIVE
scope.$parent.directiveLoaded += 1;
}
}
});
})();
Directive2
(function () {
app.directive('customDirective2', function () {
return {
restrict: 'E',
templateUrl: '/directive1.html',
link: function (scope) {
scope.function1_Of_Directive2 = function() {
console.log("F1_D2")
}
scope.function2_Of_Directive2 = function() {
console.log("F2_D2")
}
//AT BOTTOM OF EVERY DIRECTIVE
scope.$parent.directiveLoaded += 1;
}
}
});
})();