编程语言
首页 > 编程语言> > javascript – 如何使用angular的装饰器模式扩充指令的链接功能?

javascript – 如何使用angular的装饰器模式扩充指令的链接功能?

作者:互联网

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

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

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

    return $delegate;
  }
]);

使用这种模式增强原始指令的最佳方法是什么?
(示例用法:在指令上有额外的监视或额外的事件监听器,而不直接修改它的代码).

解决方法:

您可以非常轻松地修改或扩展指令的控制器.如果它是您正在寻找的链接(如您的示例中所示),那就不那么难了.只需在配置阶段修改指令的编译功能即可.

例如:

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装饰为记录值,如果它已更改.

相关的plunker在这里https://plnkr.co/edit/mDYxKj

标签:angular-directive,javascript,angularjs
来源: https://codeday.me/bug/20190829/1757364.html