【发布时间】:2015-10-14 01:50:38
【问题描述】:
背景
您可以在使用 angular.injector 方法引导您的 Angular 应用程序后调用 $compile。
angular.injector(['ng', 'late']).invoke(function($rootScope, $compile) {
$compile(myElement)($rootScope)
}
这适用于我在 late 模块上创建的指令,但不会调用我的任何 ng-bind。
示例
我在一个与我需要编译的元素不同的元素上初始化了 Angular 应用程序。
<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>
然后,一旦 angular 完成引导,我为应该稍后编译的元素创建模块和指令。
angular.element(document).ready(function() {
angular.module('late', [])
angular.module('late').controller('LateController', function($scope) {
console.log('Make controller', $scope)
$scope.lateController = true
this.clicked = 6
})
angular.module('late').directive('lateDirective', function() {
console.log('Make 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)
})
})
Play around 使用我的代码或查看output。
如果您注意到,所有的 {{ }} ng-binds 都不会被替换,而是指令模板 (lateDirective) 被插入到文档中。
问题
为什么有些指令有效而有些无效?
如何让所有指令在延迟的$compile 中正常工作?
【问题讨论】:
标签: javascript angularjs angularjs-injector