Ng-click decoration inside ng-repeat
I need to beautify ngClickDirective
to add a custom listener. This code works fine for ng-click
that is not nested inside 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 a way to make this bind
work when ng-click
nested inside ng-repeat
?
Simple plnkr to show the problem: http://plnkr.co/edit/hEkBHG7pcJfoXff523Yl?p=preview
source to share
For performance reasons, ng-repeat
will only compile the original element once. Then just clone the element and link to every element in the collection.
Hence, you must add a custom listener in link:
instead 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;
}]);
Plunker example: http://plnkr.co/edit/aGbB5LuJNtdL9JXtwNSV?p=preview
source to share