Tuesday, 20 August 2013

Decorating the ng-click directive in AngularJs

Decorating the ng-click directive in AngularJs

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 to add Google Analytics tracking to all
ng-clicks, another is to prevent double clicking.
To do this my first thought was to use a decorator. So something like this:
app.config(['$provide', function($provide) {
$provide.decorator('ngClickDirective', ['$delegate', function($delegate) {
// Trigger Google Analytics tracking here
return $delegate;
}]);
}]);
But this won't work as decorators are fired on instantiation, not when the
expression in the directive is met. So in this case it would do the
analytics when an element with the directive loads, not when the element
is clicked.
So on to the real question. Is there some way for a decorator to get at
the element that the directive is instantiated on? If I could, from the
delegate, get to the element I could bind my own click event on it to
trigger in addition to the ng-click.
If not, how would you go about adding something on all ng-clicks?

No comments:

Post a Comment