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

查看:20
本文介绍了如何使用 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.

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

Related plunker here https://plnkr.co/edit/mDYxKj

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

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