I have some logic I would like to wrap up into an AngularJS factory so I can use angular's dependency injection. Since the logic is dynamic I don't necessarily know what is available to call ahead of time. What I have is a string representing the name of the function to call. I know I can do something like window["someFunctionName"]()
to run a function with a string but since everything is wrapped up in a factory I'm not sure how to get reference to the factory to call it. ex. sampleFactory["someFuncitonName"]();
The only way I have found to run the function is using eval("someFuncitonName()")
. Obviously I would like to avoid using eval if I can.
Here is an example of what I'm trying to do:
'use strict';
angular.module('testApp')
.factory('testFactory', function (someData) {
// User defined code that was wrapped up in a factory
function foo() {
someData.amount = 5;
}
// End dynamic code
return {
funcRunner: function(functionName) {
testFactory[functionName]();
}
};
});
In the controller the user would run something like this testFactory.funcRunner("foo");
.
Is there some way to do something along these lines testFactory[functionName]();
? Is there some better way of doing this? Thanks for your help.
Update: Since the code in the comment is user defined I have no way of knowing nor do I have any control over how the code in the comments is written. I don't want to force any restrictions on the user. Therefore I can expect very little.
from what I have read there isn't a way to do this. Its just how javascript works. There is no way to call the foo function via a string. The foo function would have to be part of an object to call it with a string. I just wanted to confirm there aren't any clever ways around this.