Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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-clicks 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

like image 782
Michał Miszczyszyn Avatar asked Mar 18 '23 18:03

Michał Miszczyszyn


1 Answers

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

like image 134
runTarm Avatar answered Apr 01 '23 05:04

runTarm