How to make preventDefault links at the angle?

Asked

Viewed 481 times

4

I’m using a function called with ng-click, via a link (Anchor). However, because of the hash #, the page is "skipping" every time I click on this link.

This is my code:

<a ng-click="openImageModal(request)" href="#">
   Abrir modal
</a>

I’d like to make a preventDefault on that link, so that it could perform the function of angularjs, but without "skipping" the page, because of the hash #.

How to do this in the AngularJS?

I would like a solution without using jQuery, because I want to get rid of his dependency.

3 answers

5


  • Remove href='#'
  • add the following CSS class:

    a[ng-click]{
        cursor: pointer;
    }
    

Thus you will eliminate the default behavior while maintaining visual link feedback.

  • And the .directive?

  • @Guilhermenascimento you say in class statement or directive definition?

  • I don’t understand Angular.js, but I believe it’s in the context of angular.module. I’ll try to do, though your answer without removing the href="#" already worked perfectly, less xD maintenance code (my +1 was already guaranteed).

4

Change the href="#" for href="javascript:void(0)".

4

If you define the href empty will also work:

<a href ng-click="addNinja('OnoSedai')">Adicionar Novo Ninja</a>

The advantage of doing so is that you won’t need to define a CSS because of the absence cursor:pointer, since links without href in some browsers don’t come with cursor:pointer by default.

See it working on Ideone:

http://jsfiddle.net/Lvc0u55v/7523/

  • Needs the href empty? I know that without angular it is necessary, because if not the browser does not render as link, however I do not know the effect on angular

  • I tested here, the href empty is dispensable http://jsfiddle.net/Lvc0u55v/7524/ also, just do <a ng-click="addNinja('onoSedai')">Teste</a>, +1 for the discovery ;)

  • But the problem is cursor:Pointer @Guillhermenascimento, with href empty nor need to define a css for that :D

  • Here without the href the cursor appears normally, both with href and without.

  • But not on bootstrap.

  • Whether or not the cursor appears depends on the browser. The CSS class in my answer is used to force the behavior.

  • @Onosendai will mark your answer :). Dom will be cleaner.

  • @Wallacemaxters dome!

  • Bootstrap did not influence where I tested http://jsfiddle.net/Lvc0u55v/7525/

  • @Guilhermenascimento should be google Chrome then. I’m using the class "thumbnail" and it’s making a difference. I’ll make a fiddle

  • @Wallacemaxters understood, it must depend on the content, better to keep the href

Show 6 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.