如何在角度js中在服务中创建指令?

时间:2014-07-11 13:44:26

标签: javascript angularjs angularjs-directive angular-services

我需要在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,但它根本不起作用,我错过了什么?

1 个答案:

答案 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是我发现有助于做这些事情的文章