Decorating the ng-click directive in AngularJs

走远了吗. 提交于 2019-11-28 08:24:09

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

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