I am new to js. I have a big web app, potentially will have more than ten factories.
Here is my code. All the factory and service are in the same module
here is an example of factories
.factory('A', function(){
return function A(){
this.number;
this._id= new Date().getTime();
this.type = "A";
};
}).factory('B', function(){
return function B(){
this.type= "B";
this.number;
this._id= new Date().getTime();
};
})
And I have a service which creates new instance of factory object. the addUnit()
function actually map to users click, so the type
probably be A
, probably be B
. I know I can have functions for each of A
and B
, but because of the potential number of factories, i hope i could use only one creation function which takes type as a parameter and create new object according to the type.
.service('myService', ['A','B',
function(A, B){
this.addUnit = function(type) {
console.log(typeof A);
var myUnit = new window[type]({ //ERROR!!
'number' : 3,
});
return myUnit;
}
addUnit("A");
}])
However, the console could print out typeof A
is function, but i got an error window[type] is not a function
.
SOLUTION: Thanks @Claies ' suggestion, updated my service as below and works!
.service('myService', ['A','B',
function(A, B){
var $injector = angular.injector(['moduleName','ng']);
this.addUnit = function(type) {
console.log(typeof A);
var myUnitFunc = $injector.get(type);
var myUnit = new myUnitFunc({
'number' : 3,
});
return myUnit;
}
addUnit("A");
}])