如何使用 angular 的装饰器模式增强指令的链接功能?



我正在开发一个Angular库,并寻找一种使用decorator模式扩展指令的方法:

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发生更改时记录它。

此处为相关的plunkerhttps://plnkr.co/edit/mDYxKj

最新更新