简体   繁体   中英

Decorating ng-click inside ng-repeat

I need to decorate the ngClickDirective in order to add a custom listener. This code works fine on ng-click s which are not nested inside of ng-repeat :

$provide.decorator('ngClickDirective', ['$delegate', function ($delegate) {
    var original = $delegate[0].compile;
    $delegate[0].compile = function(element, attrs, transclude) {
        element.bind('click', function() {
            console.log('Tracking this');
        });
        return original(element, attrs, transclude);
    };
    return $delegate;
}]);

Is there any way to make this bind work when ng-click is nested inside of ng-repeat ?

Simple plnkr to show the problem: http://plnkr.co/edit/hEkBHG7pcJfoXff523Yl?p=preview

For performance reason, the ng-repeat will compile only the original element once. Then just clone the element and do the linking for each item in the collection.

Therefore, you have to add a custom listener at link: function instead of compile: like this:

$provide.decorator('ngClickDirective', ['$delegate', function ($delegate) {
    var originalCompile = $delegate[0].compile;
    $delegate[0].compile = function() {
        var originalLink = originalCompile.apply(this, arguments);

        return function postLink(scope, element, attr) {
          element.bind('click', function() {
              alert('hello!');
          });

          return originalLink.apply(this, arguments);
        };
    };
    return $delegate;
}]);

Example Plunker: http://plnkr.co/edit/aGbB5LuJNtdL9JXtwNSV?p=preview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM