5

I'm working on a library that extends some of the functionality in ui.router for building out sets of application states. Currently I am managing this by defining a new provider in my library (let's call it enhancedState) in the form:

myApp.provider('enhancedState', EnhancedState);

EnhancedState.$inject = ['$stateProvider'];
function EnhancedState ($stateProvider) {
  this.$stateProvider = $stateProvider;
}
EnhancedState.prototype = {
  /* fun new methods that wrap $stateProvider */
  $get: ['$state', function ($state) {
    /* maybe wrap some $state functionality too */
    return $state;
  }
};

I can then use my enhancedStateProvider in my application config to do fun new state definitions following the extended capabilities of my library.

I would prefer, however, to directly decorate the $stateProvider class. I am aware of Angular's $provider.decorate() utility, but as far as I can tell, it can only be used to decorate the generated service instances, not the provider.

Has anyone successfully used it to decorate providers, or is aware of a similar mechanism to do so in Angular 1.x?

Thanks!

cmw
  • 855
  • 7
  • 17

1 Answers1

5

You need AngularJS decorators (find decorator method). Check this plunker example. Based on this so post.

Example:

app.config(function($provide) {
  $provide.decorator('$state', function($delegate) {
    $delegate.customMethod = function(a) {
      console.log(a);
    };
    return $delegate;
  });
});
Community
  • 1
  • 1
Sharikov Vladislav
  • 7,049
  • 9
  • 50
  • 87
  • Correct, just it should be `$provide.decorator('$state', ...` – dfsq Nov 25 '15 at 21:48
  • Woops. Updated. I don't know anything about `$state` provider and don't know that I should inject something created as provider with `Provider` postfix. Main point was using `$provide.decorator` :) – Sharikov Vladislav Nov 25 '15 at 21:55
  • 4
    Hey, that's actually the very first thing I tried, but in my case I don't want to decorate `$state`, I want to decorate `$stateProvider`, which is the object that creates `$state`. This is what I can't find a way to reconcile with `$provide.decorator` – cmw Nov 25 '15 at 22:45
  • Anything on this issue? – Gabriel C. Troia Aug 23 '16 at 16:27
  • How would you decorate `$stateProvider` (as the OP asked)? – binki Aug 29 '18 at 23:24