使用变量调用服务和函数名称的JavaScript函数
问题描述:
在我的Angular Controller中,我需要使用变量调用函数。问题是服务和函数名都是动态定义的,所以它们都是变量。我正在使用Angular $注入器来获得没有问题的Angular服务名称。但是,函数调用不起作用:使用变量调用服务和函数名称的JavaScript函数
// serviceTypeName and functionTypeName are from the view
// vm.initiate() is invoked by ng-click
//
// $injector is injected to the controller
vm.initiate = function(serviceTypeName, functionTypeName) {
// e.g., if serviceTypeName is 'abcService' and the functionTypeName is 'foo'
// then abcService.foo() is what I hope to get.
// abcService.foo() is defined in the abcService.
var resourceService = $injector.get(serviceTypeName);
// the following works:
var data = resourceService.foo();
// the following statements do not work
var result = resourceService.functionTypeName(); // does not work
var result1 = resourceService.eval(functionTypeName)(); // does not work either
}
使用AngularJS 1.5.x可以这样做吗?如果是这样,有人可以帮我解决这个问题吗?
答
试试这个(在浏览器控制台):
var p = { myMethod: function(){console.log('called');}, myProp: 'asd' }
现在,如果你写p['myMethod']()
,你会看到越来越函数调用。以同样的方式,当你做resourceService[functionTypeName]()
时,你的函数应该被调用。
var result = resourceService[functionTypeName](); //should work
resourceService [functionTypeName](); – epascarello
这工作像一个魅力。谢谢。 – redixint