简体   繁体   English

角度 - 装饰指令

[英]Angular - Decorating Directives

I'm trying to use Angular's "decorator" capability to add functionality to some directives. 我正在尝试使用Angular的“装饰器”功能来为某些指令添加功能。 Assume that my directive's name is myDirective. 假设我的指令名称是myDirective。 My code looks like this: 我的代码看起来像这样:

angular.module('app').config([
  '$provide', function($provide) {
    return $provide.decorator('myDirective', [
      '$delegate', '$log', function($delegate, $log) {
        // TODO - It worked!  Do something to modify the behavior

        $log.info("In decorator");
      }
    ]);
  }

]); ]);

I keep getting this message: 我一直收到这条消息:

Uncaught Error: [$injector:unpr] Unknown provider: myDirectiveProvider from app 

To the best of my ability, the directives are already registered by the time the decorator function runs. 在我的能力范围内,指令在装饰器函数运行时已经注册。 Any insight would be appreciated! 任何见解将不胜感激!

This article shows how you can, in fact, use decorator() with directives. 本文展示了如何使用带有指令的decorator()。

You just have to include "Directive" as the suffix for the name. 您只需要包含“Directive”作为名称的后缀。 Hence, in my example I should have been doing 因此,在我的例子中我应该这样做

return $provide.decorator('myDirectiveDirective', ['$delegate', '$log', function($delegate, $log) {
    // TODO - It worked!  Do something to modify the behavior
    $log.info("In decorator");

    // Article uses index 0 but I found that index 0 was "window" and index 1 was the directive
    var directive = $delegate[1];
}

http://angular-tips.com/blog/2013/09/experiment-decorating-directives/ http://angular-tips.com/blog/2013/09/experiment-decorating-directives/

Decorators as created with the decorator method are for services only. 使用decorator方法创建的decorator仅用于服务 They have to be created with service , factory , provider or value . 必须使用servicefactoryprovidervalue创建它们。 See the docs here . 请参阅此处的文档。

If you want to decorate a directive, you can make another directive with the same name. 如果要装饰指令,可以使用相同的名称创建另一个指令。 Both directives will be used when the DOM is compiled, and you can define the compilation order using priority . 编译DOM时将使用这两个指令,您可以使用优先级定义编译顺序。

Alternatively, if you are able to modify the code that uses the directive you are trying to decorate, then you can just make a new directive that uses the original in its template. 或者,如果您能够修改使用您尝试装饰的指令的代码,那么您可以创建一个在其模板中使用原始指令的新指令。

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

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