Decorating the ng-click directive in AngularJs

前端 未结 2 1195
我在风中等你
我在风中等你 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;
    })
    
    0 讨论(0)
  • 2020-12-09 11:39

    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;
    });
    
    0 讨论(0)
提交回复
热议问题