在装饰的AngularJs NG-点击指令 [英] Decorating the ng-click directive in AngularJs

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

问题描述

我一直在寻找到修改AngularJS NG-点击指令添加一些额外的功能。我有什么用它来做一些不同的想法,但一个简单的就是添加谷歌Analytics跟踪到所有NG-点击,另外一种就是prevent双击。

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;
  }]);
}]);

但作为装饰是在烧制实例,而不是当该指令的前pression满足这将无法工作。因此,在这种情况下,它会做分析时与指令负载的元素,而不是被点击元素时

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-点击触发。

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-点击添加的东西吗?

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

推荐答案

您当然可以使用一个装饰增添functionnality。我做了一个快速 plunkr 来演示如何。 Basicaly,在你的装饰身上,你替换为自己的编译功能,为您定制逻辑(在本例中,如果轨道属性是present绑定到click事件),然后调用原始的编译功能。这里的片段:

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-点击指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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