Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decorating a service provider in Angular

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!

like image 470
cmw Avatar asked Nov 25 '15 21:11

cmw


1 Answers

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;
  });
});
like image 169
Sharikov Vladislav Avatar answered Sep 28 '22 03:09

Sharikov Vladislav