AngularJS - Decorator

Example demonstrating the usage of decorator to enhance a service

HTML

<body ng-app="MyApp" ng-controller="MyController">
    {{service.sayGreeting()}}
    <br/>
    {{service.sayGoodbye()}}
</body>

JavaScript

//Some other module
var otherModule = angular.module('OtherModule',[]);

// Other module has a GreetingService
otherModule.service('GreetingService', function(){
    this.sayGreeting = function() {
        return "Hello";
    };
});

// MyApp depends on OtherModule
var myApp = angular.module('MyApp', ['OtherModule']);

// MyApp is being configured with $provide injected
myApp.config(function($provide) {
    // Decorate the GreetingService
    // Service instance from OtherModule is injected as $delegate
    $provide.decorator('GreetingService', function($delegate){
       
        $delegate.sayGreeting = function() {
            return "function delegated!";
        };
        
        return $delegate;
        
        
    });
    
    
    
});

// The injected GreetingService in this module will be the decorated service
myApp.controller("MyController", function($scope, GreetingService){
    $scope.service = GreetingService;
});