使用服务和函数名称的变量调用JavaScript函数

时间:2017-05-08 17:20:24

标签: javascript angularjs

在我的Angular Controller中,我需要使用变量调用函数。问题是服务和函数名称都是动态定义的,所以它们都是变量。我使用Angular $ injector来获取Angular服务名称没有问题。但是,函数调用不起作用:

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

1 个答案:

答案 0 :(得分:-1)

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

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

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

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