Search code examples
angularjsangularjs-factory

Factory methods in multiple files Angular JS


What is the best practice when you have a Factory with like 4 related methods, each of those is really long (200+ lines of code) and you want to avoid having a huge file of 800+ lines of code?

One solution is to create 4 factories under the same module , each one exposing a single method and in its own file. Then inject all of them in the controller that requires them.

Is there a better solution? I'd like to create the Factory once, then add methods to it like I was doing module augmentation using the module pattern. Then I just need to inject the Factory once and have all its methods available.


Solution

  • You could also arrange your code the old vanilla js style and then access those libraries in your services like this:

    var Mirko = { };
    
    Mirko.FunService = {
      getAllSomething : function (p1, p2) {
      },
      ...
    };
    
    angular.module('myModule').factory('BigService', function(){
      return {
        methodOne : Mirko.getAllSomething,
        ...
      };
    });
    

    You will end up with one object Mirko that you can access outside the scope of your angular app, but it will in no way differ from other externals api's (not written for angular) you would want to use in your app. The way you handle your own 'external' api can be done the oldschool fashion way, one file per 'class' e.g. 'FunService'.

    It might not be the prettiest solution but it will be an easy abstraction.

    Just saying...