From 8248e77a7b910bcbc71ca25c06bef44dd6712990 Mon Sep 17 00:00:00 2001 From: Igor Minar Date: Thu, 30 Sep 2010 23:07:36 +0800 Subject: 'A' tag widget and ng:click propagation change * added a widget for A (anchor) tag, that modifies the default behavior and prevent default action (location change and page reload) for tags with empty href attribute * stopped event propagation for all ng:click handlers --- src/directives.js | 11 ++++++++++- src/widgets.js | 22 ++++++++++++++++++++++ test/directivesSpec.js | 13 +++++++++++++ test/widgetsSpec.js | 35 +++++++++++++++++++++++++++++++++++ 4 files changed, 80 insertions(+), 1 deletion(-) diff --git a/src/directives.js b/src/directives.js index 69648e31..4443cc9d 100644 --- a/src/directives.js +++ b/src/directives.js @@ -198,13 +198,22 @@ angularWidget("@ng:repeat", function(expression, element){ }; }); + +/* + * A directive that allows creation of custom onclick handlers that are defined as angular + * expressions and are compiled and executed within the current scope. + * + * Events that are handled via these handler are always configured not to propagate further. + * + * TODO: maybe we should consider allowing users to control even propagation in the future. + */ angularDirective("ng:click", function(expression, element){ return function(element){ var self = this; element.bind('click', function(event){ self.$tryEval(expression, element); self.$root.$eval(); - event.preventDefault(); + event.stopPropagation(); }); }; }); diff --git a/src/widgets.js b/src/widgets.js index fbca8436..24eba900 100644 --- a/src/widgets.js +++ b/src/widgets.js @@ -340,3 +340,25 @@ var ngSwitch = angularWidget('ng:switch', function (element){ }, route: switchRouteMatcher }); + + +/* + * Modifies the default behavior of html A tag, so that the default action is prevented when href + * attribute is empty. + * + * The reasoning for this change is to allow easy creation of action links with ng:click without + * changing the location or causing page reloads, e.g.: + * Save + */ +angular.widget('a', function() { + this.descend(true); + this.directives(true); + + return function(element) { + if (element.attr('href') === '') { + element.bind('click', function(event){ + event.preventDefault(); + }); + } + }; +}); \ No newline at end of file diff --git a/test/directivesSpec.js b/test/directivesSpec.js index f0eb5c09..72f7b2f2 100644 --- a/test/directivesSpec.js +++ b/test/directivesSpec.js @@ -169,6 +169,19 @@ describe("directives", function(){ element.trigger('click'); expect(scope.$get('clicked')).toEqual(true); }); + + it('should stop event propagation', function() { + var scope = compile('