Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 261
blaster Avatar asked Oct 16 '13 16:10

blaster


People also ask

What are decorators and directives in Angular?

Decorators are design patterns used to isolate the modification or decoration of a class without modifying the source code. In AngularJS, decorators are functions that allow a service, directive, or filter to be modified before it is used.

Which decorator is used for directive?

We create a directive by decorating a class with the @Directive decorator. The convention is to associate a directive to an element via an attribute selector, that is the name of the attribute wrapped in [] . We can inject a reference to the element the directive is associated with to the constructor of the directive.

What are decorative in Angular?

What Angular Decorators Do. The whole purpose of Angular decorators is to store metadata about a class, method, or property. When you configure a component, you are providing a metadata for that class that tells Angular that you have a component, and that component has a specific configuration.

What are the directives of Angular?

In Angular, Directives are defined as classes that can add new behavior to the elements in the template or modify existing behavior. The purpose of Directives in Angular is to maneuver the DOM, be it by adding new elements to DOM or removing elements and even changing the appearance of the DOM elements.


1 Answers

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/

like image 196
blaster Avatar answered Oct 14 '22 22:10

blaster