在ng-repeat内部装饰ng-click

时间:2014-08-13 08:32:51

标签: javascript angularjs angularjs-ng-repeat

我需要修饰ngClickDirective才能添加自定义侦听器。此代码在ng-click上没有嵌套在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;
}]);

bind嵌套在ng-click内时,有没有办法让ng-repeat工作?

简单的plnkr来显示问题:http://plnkr.co/edit/hEkBHG7pcJfoXff523Yl?p=preview

1 个答案:

答案 0 :(得分:6)

出于性能原因,ng-repeat将仅编译原始元素一次。然后只需克隆元素并为集合中的每个项目进行链接。

因此,您必须在link:函数而不是compile:添加自定义侦听器,如下所示:

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

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