我需要在angular服务中创建一个指令,然后在一个带有该指令的事件插入元素到dom并编译它,插入和编译似乎工作正常,但似乎从angular内部动态创建的指令(控制器) ,服务或任何地方)不要注册或其他什么。
这是我当前代码的简化版
var dirs = angular.module('dirs', []);
dirs.factory('directiveCreator', function($rootScope) {
var creator = {};
creator.addDirective = function(config) {
dirs.directive(config.name, function() {
return {
restrict: config.restrict,
template: config.template,
replace: config.replace,
}
});
//insert element with the directive above into DOM on this event and compile
$rootScope.$broadcast('directive.added');
}
return creator;
}
该指令在模块上正确添加到invokeQueue,但它根本不起作用,我错过了什么?
答案 0 :(得分:3)
您需要捕获$compileProvider
,然后使用directive
方法,而不是使用moduleObj.directive
方法
var dirs = angular.module('dirs', []);
dirs.config(function($compileProvider){
dirs.compileProvider = $compileProvider;
});
然后当你需要动态包含新指令
时creator.addDirective = function(config) {
dirs.compileProvider.directive(config.name, function() {
return {
restrict: config.restrict,
template: config.template,
replace: config.replace,
}
});
//insert element with the directive above into DOM on this event and compile
$rootScope.$broadcast('directive.added');
}
这是延迟加载,Here是我发现有助于做这些事情的文章