mercoledì 2 luglio 2014

preventDefault and stopPropagation for anchors in AngularJS

Sometimes in an application we use anchor tags to trigger functions on our controller like the following:

<a href="#" data-ng-click="doSomething()">Click me</a<>

This is not a best practice, but in some cases you need to use it anyways. In this case you need to tell the browser to not to handle the anchor like a link and reload the page.

In plain javascript is really simple:

HTML
<a href="#" onclick="doSomething()">Click me</a>

Javascript
...
function doSomething(event)
{
    event.preventDefault();
    event.stopPropagation();

    alert("Hello, world!");
}
...

But now, you want to do this with AngularJS. It's really simple, like in plain javascript. So, you'll write:

HTML
<a href="#" data-ng-click="doSomething(); $event.preventDefault(); $event.stopPropagation();">Click me</a>

Javascript
...
$scope.doSomething = function()
{
    alert("Hello, world!");
}
...