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

问题描述:

我想在指令中重复使用某些模式,例如使用数据列表对模式进行调用。在模式中,将会有一种获取数据的方法,并且该方法在服务中定义。该服务是通过从视图传递的参数动态生成的。但我不知道如何获得服务函数并在指令中调用它(而不是在testCtrl中)。 下面是一个示例代码:如何在AngularJS的指令中通过函数名称调用/获取服务函数?

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> 

谢谢!

更新问题: 我试图通过潘卡提出的解决方案,我发现该服务的功能如下: enter image description here为什么这看起来像一个匿名函数?

嗯,事实上,我想用服务功能更像是传递函数作为参数(如以下):

service.getData(serviceFunction,当前页,currentPageSize,XXXX).success(功能(){....})

和serviceFunction将被称为service.getData里面,像这样: enter image description here

但与“匿名函数”(对不起,我不知道我称这是正确的),这是行不通的。任何人都可以详细阐述一点吗?我完全困惑,为什么这不适用于指令。

而不是有element.injector()你应该使用$injector获得service的实例来解决从模块的依赖性。

当您使用@(单向)通过serviceName & serviceMethod结合,你应该在{{}}插值使用合格值。

标记

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

代码

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

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

感谢潘卡。由于我对AngularJS相当陌生,请您介绍一下为什么我应该在这里使用{{}}插值以及为什么service [XX]可以获得服务功能?并且请看更新,我发现在这种情况下,service [attrs.serviceMethod]将不起作用。非常感谢! – Spencer

+0

你是正确的..那是我的坏..看更新.. –

+0

谢谢潘卡。随着服务[scope.serviceMethod]这将工作。发现后,我们应该使用service [scope.serviceMethod]而不是service [scope.serviceMethod]()。你知道我为什么可以通过使用'[]'来达到服务返回功能(该服务由工厂定义)吗? – Spencer