Want to preventDefault on anchor tags? I prefer to use directives for this kind of thing. Here’s an example:
1 | <a href="#" ng-click="do()" eat-click>Click Me</a> |
And the directive code for eat-click:
1 2 3 4 5 6 7 | module.directive('eatClick', function() { return function(scope, element, attrs) { $(element).click(function(event) { event.preventDefault(); }); } }) |
Now you can add the eat-click attribute to any element and it will get preventDefault()’ed automagically.
Benefits:
1. You don’t have to pass the ugly $event object into your do() function.
2. Your controller is more unit testable because it doesn’t need to stub out the $event object.
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.