Insight
In order to execute the $compile
function after your angular application is up and running, you can utilize the angular.injector
method.
angular.injector(['ng', 'late']).invoke(function($rootScope, $compile) {
$compile(myElement)($rootScope)
}
While this method successfully triggers directives created within the late
module, it may not engage any of the ng-bind
directives.
Illustration
The initiation of my angular app occurs on a distinct element separate from those requiring compilation.
<div ng-app="test">
</div>
<div id="uncompiled">
{{ $id }}
<div ng-controller="LateController as cont">
{{ $id }} {{ "5" }} {{ cont.clicked }}
<div late-directive="5"></div>
</div>
</div>
Following the completion of angular bootstrapping, I proceed to establish the necessary modules and directives for elements designated for delayed compilation.
angular.element(document).ready(function() {
angular.module('late', [])
angular.module('late').controller('LateController', function($scope) {
console.log('Creating controller', $scope)
$scope.lateController = true
this.clicked = 6
})
angular.module('late').directive('lateDirective', function() {
console.log('Generating directive')
return {
restrict: 'A',
template: '<span>INNEREST {{ $id }}</span> COMPILED LATE!!! {{ $id }} {{ cont.clicked }}',
}
})
angular.injector(['ng', 'late']).invoke(function($compile, $rootScope) {
console.log('Injecting')
var el = angular.element(document.getElementById('uncompiled'))
$compile(el)($rootScope)
})
})
Experiment with the code or view the result.
If you observe closely, while the directive templates are successfully embedded, the {{ }}
ng-binds do not get substituted.
Inquiry
Why do certain directives function correctly while others do not?
How can all directives be effectively executed within the deferred $compile
process?