AngularJS:在多个指令中重构代码逻辑

AngularJS:在多个指令中重构代码逻辑,angularjs,refactoring,Angularjs,Refactoring,我有一系列指令,它们有相同的逻辑: angular.module('playrApp').directive('oneofmydirective', [ function() { 'use strict'; return { restrict: 'E', replace: true, scope: { listeners: '@' }, link: function($scope, $element)

我有一系列指令,它们有相同的逻辑:

angular.module('playrApp').directive('oneofmydirective', [
  function() {
    'use strict';
    return {
      restrict: 'E',
      replace: true,
      scope: {
        listeners: '@'
      },
      link: function($scope, $element) {
        $scope.listeners = [].concat(($scope.listeners||'').split(' '));

        _.forEach($scope.listeners, function(listener){
          $scope.$on(listener, $scope['on'+listener]);
        });
      },
      unlink: function($scope, $element) {
        _.forEach($scope.listeners, function(listener){
          $scope.$off(listener, $scope['on'+listener]);
        });

      },
      controller: ['$scope', '$element',
        function($scope, $element) {

          $scope.onMyCustomEvent1 = function() {
            // handle event
          };
          $scope.onMyCustomEvent2 = function() {
            // handle event
          };

        }]
    }
  ]);
因此,我可以根据需要使用它们激活或不激活侦听器:

<!-- Sometimes -->
<oneofmydirective></oneofmydirective>
<!-- And sometimes -->
<oneofmydirective listeners="MyCustomEvent1 MyCustomEvent2"></oneofmydirective>


我如何重构代码以在每个指令中共享它?

澄清一下:您想拥有同一指令的多个实例,并让它们对侦听器属性中指定的某些事件做出反应?不,我有多个指令
oneofmydirective
另一个指令
等,它们有特定的行为(模板、控制器等),但都有我在上面写的代码。请编写一个工厂,为您实例化共享逻辑函数。然后将其注入需要共享逻辑的指令。不确定如何将此应用于您的示例,因此懒得提供答案。因为您总是返回一个指令定义对象,所以您有机会向它们“混合”行为。组合或继承-在您的情况下不确定。那对你有用吗?可以将服务注入到指令中。示例如下: