Search code examples
javascriptangularjsgoogle-chrome-devtoolsfactoryangularjs-factory

Update angualar.js factory from chrome dev. tools


Is there a way to override the downloaded angular.js factory from dev tools.
I want to add some log statements from the client as I cannot do by deploying code. Normal Javascript functions could be updated easily just by running the updated function in console.
But, I am unable to do that for angular.js factories


Solution

  • The general answer is there's no way. Angular services are singletons, and once the service was instantiated, the instance is stored in private variable with no opportunity to override it.

    However, if the factory was instantiated as an object with a bunch of methods, the methods can be monkey-patched:

    var factory = angular.element(document.querySelector('.ng-scope'))
      .injector()
      .get('factoryName');
    
    var factoryMethod = factory.methodName;
    factory.methodName = function () {
      console.log(arguments);
      return factoryMethod.apply(factory, arguments);
    };
    

    In other cases the recipe is to hijack the app during bootstrapping process with Greasemonkey / Tampermonkey. This makes it possible to provide the entire new module that overrides components from the original module. Or provide an additional config block to the original module, where defined factory can be modified with $provide.decorator or redefined with $provide.factory.