我需要在 Angular 服务中创建一个指令,然后在带有该指令的事件插入元素到 dom 中并编译它,插入和编译似乎工作正常,但似乎指令是从 Angular 内部动态创建的( Controller ,服务或任何地方)不要注册或其他东西。
这是我当前代码的简化版本
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,但它根本不起作用,我是否遗漏了什么?
最佳答案
您需要捕获$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是一篇我发现对做这些事情很有帮助的文章
关于javascript - 如何在 angular js 中的服务内创建指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24699245/