Search code examples
javascriptangularjsangularjs-factorydynamic-variables

How to call a factory method dynamically coming from variable?


I have a service which will return the name of factory. I already injected all the factories into controller. I need to use the variable to call the method inside that factory. I know i can use

if(var == 'factoryname') {
     factoryname.method()
}

but i don't want those if conditions because i have number of factories. Is there any way to call a method inside that factory like in java script
window[var]


Solution

  • You should consider storing all of your factories on an object:

    var factories = {
      factoryA: { method: function() {} },
      factoryB: { method: function() {} },
    };
    
    var factory = 'factoryA';
    
    factories[factory].method();