简体   繁体   中英

Angular - Decorating Directives

I'm trying to use Angular's "decorator" capability to add functionality to some directives. Assume that my directive's name is 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.

You just have to include "Directive" as the suffix for the name. 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/

Decorators as created with the decorator method are for services only. They have to be created with service , factory , provider or value . 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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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