Decorating the ng-click directive in AngularJs

前端 未结 2 1197
我在风中等你
我在风中等你 2020-12-09 10:38

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 t

2条回答
  •  执念已碎
    2020-12-09 11:38

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

提交回复
热议问题