timothym
timothym

Reputation: 3265

Prevent ng-click expression from firing on enter keydown

I have a simple button like this:

<button type="button" ng-click="$ctrl.method($event)">Test</button>

Here's what the ng-click expression looks like:

vm.method = function($event) {
    console.log($event.type, $event.which);
};

When this button has focus (by way of navigating to it via the tab key) and I press enter, I get this output to the console:

click 1

To be more clear that's $event.type == 'click' and $event.which == 1.

I'm not sure why the ng-click directive allows the enter key to fire the assigned expression. Angular is recording enter keydown events as clicks. Is there a way to prevent this and have ng-click only handle click events (and ignore enter)?

This trivial bit of code is just an example, in my app I would like to use both ng-keydown and ng-click on the same component, but this particular issue is preventing me from fully implementing the functionality I want. Ideally, I'd like to have ng-keydown only handle keydown events, and ng-click only handle click events.

Upvotes: 0

Views: 1707

Answers (3)

Anthony Gingrich
Anthony Gingrich

Reputation: 223

If your button is inside a form and it's the only button, the click event will be fired on enter when the form has focus, depending upon the browser. You should be able to check the event object in your handler method and return false if it's the enter key triggering.

https://docs.angularjs.org/guide/expression#-event-

Upvotes: 0

Sereja Nagin
Sereja Nagin

Reputation: 86

Possible but not best way is to check screenX/screenY/pageX/pageY/offsetX... props of $event. In case of "enter" they are equal to zero.

Upvotes: 1

Tremmillicious
Tremmillicious

Reputation: 506

Just prevent default on the key press e.g.

 vm.method = function($event)   {    
    if($event.keyCode === 13){ //I think
       $event.preventDefault();
    }   
    console.log($event.type, $event.which);
};

Upvotes: 0

Related Questions