如何使用 angular 的装饰器模式来增强指令的 link 函数?

How can I augment a directive's link function with angular's decorator pattern?

我正在研究 Angular 库并寻找一种使用装饰器模式扩展指令的方法:

angular.module('myApp', []).decorator('originaldirectiveDirective', [
  '$delegate', function($delegate) {

    var originalLinkFn;
    originalLinkFn = $delegate[0].link;

    return $delegate;
  }
]);

使用此模式扩充原始指令的最佳方法是什么? (示例用法:在不直接修改其代码的情况下对指令进行额外的监视或额外的事件侦听器)。

您可以很容易地修改或扩展指令的 controller。如果它是 link 你正在寻找的(如你的例子),它并没有那么难。只需在 config 阶段修改指令的 compile 函数。

例如:

HTML模板

<body>
  <my-directive></my-directive>
</body>

JavaScript

angular.module('app', [])

  .config(function($provide) {
    $provide.decorator('myDirectiveDirective', function($delegate) {
      var directive = $delegate[0];

      directive.compile = function() {
        return function(scope) {
          directive.link.apply(this, arguments);
          scope.$watch('value', function() {
            console.log('value', scope.value);
          });
        };
      };

      return $delegate;
    });
  }) 

  .directive('myDirective', function() {
    return {
      restrict: 'E',
      link: function(scope) {
        scope.value = 0; 
      },
      template: '<input type="number" ng-model="value">'
    };
  });

现在您已经装饰 myDirective 以记录 value 当它发生变化时。

相关插件在这里https://plnkr.co/edit/mDYxKj