在 AngularJs 中装饰 ng-click 指令 [英] Decorating the ng-click directive in AngularJs

查看:23
本文介绍了在 AngularJs 中装饰 ng-click 指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究修改 AngularJS ng-click 指令以添加一些附加功能.我对它的用途有一些不同的想法,但一个简单的想法是将 Google Analytics 跟踪添加到所有 ng-clicks,另一个是防止双击.

I've been looking into modifying the AngularJS ng-click directive to add some additional features. I have a few different ideas of what to use it for, but a simple one is to add Google Analytics tracking to all ng-clicks, another is to prevent double clicking.

为此,我的第一个想法是使用装饰器.所以是这样的:

To do this my first thought was to use a decorator. So something like this:

app.config(['$provide', function($provide) {
  $provide.decorator('ngClickDirective', ['$delegate', function($delegate) {
    // Trigger Google Analytics tracking here
    return $delegate;
  }]);
}]);

但这不会起作用,因为装饰器是在实例化时触发的,而不是在满足指令中的表达式时触发.因此,在这种情况下,它会在带有指令的元素加载时进行分析,而不是在点击该元素时进行分析.

But this won't work as decorators are fired on instantiation, not when the expression in the directive is met. So in this case it would do the analytics when an element with the directive loads, not when the element is clicked.

接下来才是真正的问题.装饰器有什么方法可以获取指令实例化的元素吗?如果我可以从委托获得元素,除了 ng-click 之外,我还可以在其上绑定我自己的点击事件以触发.

So on to the real question. Is there some way for a decorator to get at the element that the directive is instantiated on? If I could, from the delegate, get to the element I could bind my own click event on it to trigger in addition to the ng-click.

如果没有,您将如何在所有 ng-click 中添加一些内容?

If not, how would you go about adding something on all ng-clicks?

推荐答案

您当然可以使用装饰器来添加功能.我制作了一个快速的 plunkr 来演示如何操作.基本上,在您的装饰器主体中,您将 compile 函数替换为您自己的自定义逻辑(在示例中,如果存在 track 属性,则绑定到 click 事件),然后调用原始 compile 函数.这是片段:

You can certainly use a decorator to add functionnality. I've made a quick plunkr to demonstrate how. Basicaly, in your decorator body, you replace the compile function with your own for your custom logic (in the example, binding to the click event if the track attribute is present) and then call the original compile function. Here's the snippet:

$provide.decorator('ngClickDirective', function($delegate) {
  var original = $delegate[0].compile;
  $delegate[0].compile = function(element, attrs, transclude) {
    if(attrs.track !== undefined) {
      element.bind('click', function() {
        console.log('Tracking this');
      });
    }
    return original(element, attrs, transclude);
  };
  return $delegate;
})

这篇关于在 AngularJs 中装饰 ng-click 指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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