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!
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.
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 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.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With