Decorating the ng-click directive in AngularJs

帅比萌擦擦* 提交于 2019-12-17 18:39:20

问题


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.

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.

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


回答1:


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



回答2:


This is the correct updated version (improved from the answer):

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


来源:https://stackoverflow.com/questions/18335574/decorating-the-ng-click-directive-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!