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

时间:2015-05-14 17:27:02

标签: angularjs refactoring

我有一堆指令,他们有相同的逻辑:

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>

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

0 个答案:

没有答案