如何使用angular的装饰器模式扩充指令的链接功能? [英] How can I augment a directive's link function with angular's decorator pattern?

查看:40
本文介绍了如何使用angular的装饰器模式扩充指令的链接功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm working on an Angular library and looking for a way to extend a directive using the decorator pattern:

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

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

    return $delegate;
  }
]);

使用此模式来扩展原始指令的最佳方法是什么? (示例用法:在指令上具有其他监视程序或事件监听器,而无需直接修改其代码).

What would be the best way to augment the original directive using this pattern? (Example usage: to have additional watches or extra event listeners on the directive without modifying it's code directly).

推荐答案

您可以很容易地修改或扩展指令的controller.如果您要查找的是link(如您的示例中所示),那么难度就没有那么大了.只需在config阶段修改指令的compile函数.

You can modify or extend directive's controller quite easily. If it's link you are looking for (as in your example), it's not that much harder. Just modify directive's compile function in config phase.

例如:

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更改时登录.

Now you have decorated myDirective to log value when ever it has changed.

此处的相关监听器 https://plnkr.co/edit/mDYxKj

这篇关于如何使用angular的装饰器模式扩充指令的链接功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆