使用服务和函数名的变量调用JavaScript函数
在我的角度控制器中,我需要使用变量调用函数。问题是服务和函数名都是动态定义的,所以它们都是变量。我正在使用Angular$injector毫无问题地获取Angular服务名称。但是,函数调用不起作用:使用服务和函数名的变量调用JavaScript函数,javascript,angularjs,Javascript,Angularjs,在我的角度控制器中,我需要使用变量调用函数。问题是服务和函数名都是动态定义的,所以它们都是变量。我正在使用Angular$injector毫无问题地获取Angular服务名称。但是,函数调用不起作用: // serviceTypeName and functionTypeName are from the view // vm.initiate() is invoked by ng-click // // $injector is injected to the controller vm.
// 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可以这样做吗?如果是,有人能帮我解决这个问题吗?试试这个(在浏览器控制台中):
现在,如果您编写
p['myMethod']()
,您将看到函数被调用。同样,当您执行resourceService[functionTypeName]()
时,您的函数应该被调用
var result = resourceService[functionTypeName](); //should work
resourceService[functionTypeName]();这很有魅力。谢谢。@redixint-如果这对您有效,您可以将其标记为答案。其他用户将知道问题已经得到解决
var result = resourceService[functionTypeName](); //should work