Voles Voles - 1 year ago 50
AngularJS Question

Prevent default anchor behaviour AngularJS

When the user clicks a link, I want to execute some code in a function inside the controller. But I want to prevent that the URL changes.

I tried the following possibilities

  1. Removed the href-attribute. Didn't work, still changes the url to '/'

  2. Tried
    ng-click='deleteUser(user.id, $event)'
    in my deleteUser()-function. Didn't work.

  3. What did work is a hack I've found on GitHub about an unintended reload.

This is how I do it now:

<a ng-click="deleteUser(user.id)" href="javascript:">Delete user</a>


What is the'clean' method to prevent a link from changing the URL?

Answer Source

The real problem is in the a directive

That's right, every <a></a> element is actually an AngularJS directive.

It seems to fix some issues with IE if you look the comments in the code.

But everything for me is working great when I just removed the directive from the AngularJS core code.

I was having the same problem as you did and tried all of the other solutions. The difference is that I had the problem only in IE.

If you don't want to play with building the AngularJS script from source, just search for htmlAnchorDirective in the angular.js file and remove/comment it out.

I believe there is a bigger problem here which should be addressed in the AngularJS core, but I haven't found it yet.

UPDATE: This solution is most probably outdated now! You should try using the latest AngularJS version.