2017-05-08 86 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