AngularJS Example: DI for Services

for http://stepansuvorov.com/blog/

by Stepan Suvorov

CSS

</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ --> 
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>

JavaScript

angular.module('foo', [])
   .service('simpleService', function(){ this.name = "foo"; });

angular.module('bar', ['foo'])
   .config(function($provide){

      //$provide was injected for me automatically by Angular
      $provide.decorator('simpleService', function($delegate){

         //$delegate is the service instance, and is
         // also injected automatically by Angular
         $delegate.name += "|bar";

  return $delegate;
      });
   });

var fooSvc = angular.injector(['foo']).get('simpleService');
var barSvc = angular.injector(['bar']).get('simpleService');

console.log(fooSvc.name); // 'foo'
console.log(barSvc.name); // 'foo|bar'