2017-05-08 84 views
-1

在我的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可以这样做吗?如果是这样,有人可以帮我解决这个问题吗?

+0

resourceService [functionTypeName](); – epascarello

+0

这工作像一个魅力。谢谢。 – redixint

回答

-1

试试这个(在浏览器控制台):

var p = { myMethod: function(){console.log('called');}, myProp: 'asd' } 

现在,如果你写p['myMethod'](),你会看到越来越函数调用。以同样的方式,当你做resourceService[functionTypeName]()时,你的函数应该被调用。

var result = resourceService[functionTypeName](); //should work 
+0

这工作。谢谢。 – redixint

+0

@redixint - 如果这适用于您,您可以将其标记为答案。其他用户会知道问题已经得到解决 – Paritosh

相关问题