Tuesday 16 February 2016

How to create a service decorator and controller decorator in angular 1.3 and above

How to create a service decorator and controller decorator in angular 1.3 and above

(function () {
    "use strict";

    function logProvider($provide) {
        $provide.decorator('deAllocationService', function ($delegate) {
           //Store original functions
            var getAllocationsFn  = $delegate.getAllocations;
            //Decorate the function
            $delegate.getAllocations = function () {
                //decorating original function with a console log statement just as an example
               console.log('I am a decorated function');
                //get the arguments of the original function
                var args    = [].slice.call(arguments);
                //call the original function
                return getAllocationsFn.apply(null,  args);
            };
          return $delegate;
        });

        $provide.decorator('$controller', function ($delegate) {
            return function (constructor, locals, later, indent) {
                // You can store the original function like below
                // You have to know the name of originalFn - Original Function
                //var original = $delegate.originalFn();

                // here decorate the controller's function

                //return original function
                return $delegate.apply(null, arguments);
            };
        });
    }

    module.exports = logProvider;
}());