简体   繁体   English

在配置块外部使用angular compileProvider

[英]Use angular compileProvider outside config block

I'm trying to create directives on the fly, actually I achived that, but seams pretty hacky. 我正在尝试动态创建指令,实际上我已经实现了这一点,但接缝非常糟糕。

This was my first approach: 这是我的第一个方法:

function create(myDir) {
   angular.module("app").directive(myDir.name, function() {
   return {
     template:myDir.template
   };
  });
}

It didn't work because you can't register directives after application started. 它不起作用,因为您无法在应用程序启动后注册指令。

based on this post: http://weblogs.thinktecture.com/pawel/2014/07/angularjs-dynamic-directives.html 根据这篇文章: http//weblogs.thinktecture.com/pawel/2014/07/angularjs-dynamic-directives.html

I found out that I could use compileProvider to do the work, but since compileProvider isn't available outside config block, you need to put it out, so I did: 我发现我可以使用compileProvider来完成这项工作,但由于compileProvider在config block之外不可用,你需要把它拿出来,所以我做了:

var provider = {};
angular.module("app",[]);        

angular.module('app')
.config(function ($compileProvider) {
    //It feels hacky to me too.
    angular.copy($compileProvider, provider);
 });
....

function create(myDir) {
    provider.directive.apply(null, [myDir.name, function () { 
        return { template: myDir.template } }]);
    render(myDir); //This render a new instance of my new directive
}

Surprisingly it worked. 令人惊讶的是它有效。 But I can't feel like being hacking the compileProvider , because I'm using it not in the way it was suppose to be, I would really like to know if is it possible to use the compileProvider properly after the application has started. 但我不能感觉自己是在攻击 compileProvider ,因为我使用的不是它想象的方式,我真的想知道在应用程序启动后是否可以正确使用compileProvider

There is a list of dependencies that can be injected to config blocks (these are built-in $provide , $injector and all service providers) and a list of dependencies that can be injected to everywhere else (service instances and good old $injector ). 有一个可以注入config块的依赖项列表(这些是内置的$provide$injector和所有服务提供程序)和一个可以注入其他地方的依赖项列表(服务实例和旧的$injector ) 。 As you can see all that constant does is adding the dependency to both lists . 正如您所看到的那样, constant将依赖项添加到两个列表中

A common recipe for using providers outside config is config之外使用提供程序的常见方法是

app.config(function ($provide, $compileProvider) {
  $provide.constant('$compileProvider', $compileProvider);
});

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

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