简体   繁体   English

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

[英]How to create a directive inside a service in angular js?

I need to create a directive inside angular service and then on an event insert element with that directive into dom and compile it, the inserting and compiling seems to be working fine, but it seems that directives created dynamically from inside angular (controller, service or wherever) don't register or something. 我需要在angular服务中创建一个指令,然后在带有该指令的事件插入元素中创建dom并编译它,插入和编译似乎工作正常,但似乎从angular内部动态创建指令(控制器,服务或在哪里)不注册或什么的。

Here's a simplified version of my current code 这是我当前代码的简化版本

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;
}

The directive is added to invokeQueue properly on the module, but it doesn't work at all, am I missing something? 该指令在模块上正确添加到invokeQueue,但它根本不起作用,我错过了什么?

you need to capture the $compileProvider and then use the directive method instead of using the moduleObj.directive method 你需要捕获$compileProvider ,然后使用directive方法而不是使用moduleObj.directive方法

var dirs = angular.module('dirs', []);
dirs.config(function($compileProvider){
   dirs.compileProvider = $compileProvider;
});

then when you need to dynamically include the new directive 然后当你需要动态包含新指令时

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');
}

This is lazy loading, Here is an article that I found helpful in doing such things 这是延迟加载, 是一篇我发现有助于做这些事情的文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM