在我的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可以這樣做嗎?如果是這樣,有人可以幫我解決這個問題嗎?
resourceService [functionTypeName](); – epascarello
這工作像一個魅力。謝謝。 – redixint