如何在AngularJS中通过指令中的函数名调用/获取服务函数?

如何在AngularJS中通过指令中的函数名调用/获取服务函数?,angularjs,service,ionic-framework,directive,Angularjs,Service,Ionic Framework,Directive,我想在指令中重用一些模式,比如带有数据列表的modal poped。在模式中,将有一个获取数据的方法,该方法在服务中定义。该服务是通过从视图传递的参数动态生成的。但是我不知道如何获取服务函数并在指令中调用它(而不是在testCtrl中)。 下面是一个示例代码: angular.module('app',[ionic]).controller('testCtrl', function(customerService, productService){

我想在指令中重用一些模式,比如带有数据列表的modal poped。在模式中,将有一个获取数据的方法,该方法在服务中定义。该服务是通过从视图传递的参数动态生成的。但是我不知道如何获取服务函数并在指令中调用它(而不是在testCtrl中)。 下面是一个示例代码:

 angular.module('app',[ionic]).controller('testCtrl', function(customerService, productService){
                         //some controller function
                });

     angular.module('app').factory('customerService',function(){
            return{
                    getCustomers:fuction(){...}
                  }
     });

     angular.module('app').factory('productService',function(){
            return{
                    getProducts:function(){...}
                  }
     });    



angular.module('app').directive('chooseModal',function(){
              var linkFunc = function (scope, ele, attrs) {

          /**This gets the service instance**/
          var service = ele.injector().get(scope.serviceName);

          scope.getData = function(){

            //How to call the service function like getCustomers/getProducts here(the function name can be got through the scope.serviceMethod)?

          }
         }

         return {
           restrict: 'EA',
           scope: {
                    templateUrl: "@templateUrl",
                    serviceName: '@',
                    serviceMethod:'@'
                   },
           link: linkFunc
         };
})
视图的定义如下:

  <input type="text" template-url="XXX" service-name="customerService" service-method="getCustomers" choose-modal>

提前谢谢

更新问题: 我尝试了Pankaj提出的解决方案,发现服务功能如下: . 为什么这看起来像一个匿名函数?

实际上,我想使用的服务函数更像是将函数作为参数传递(如下所示):

getData(serviceFunction,currentPage,currentPageSize,xxxx).success(function(){..})

serviceFunction将在service.getData中调用,如下所示:


但是使用“匿名函数”(抱歉,我不知道我是否正确调用了此函数),这将不起作用。谁能再详细一点吗?我完全不明白为什么这在指令中不起作用。

而不是有
元素。injector()
您应该使用
$injector
获取
服务的实例,以解决模块的依赖关系

使用
@
(单向)绑定传递
serviceName
serviceMethod
时,应在
{}
插值中使用传递值

标记

<input type="text" template-url="XXX" 
  service-name="{{'customerService'}}" 
  service-method="{{'getCustomers'}}" choose-modal>

谢谢潘卡吉。因为我对AngularJS很陌生,你能解释一下为什么我应该在这里使用{{}}插值,以及为什么服务[XX]可以获得服务函数吗?请查看更新,我发现在这种情况下,服务[attrs.serviceMethod]将无法工作。非常感谢!谢谢潘卡吉。对于服务[scope.serviceMethod],这将起作用。我们应该使用服务[scope.serviceMethod],而不是服务[scope.serviceMethod]()。您知道为什么我可以通过使用“[]”来访问服务返回函数(服务由工厂定义)?
/**This gets the service instance**/
var service = $injector.get(scope.serviceName);

scope.getData = function() {
  //this would call service method.
  service[scope.serviceMethod]();
}