AngularJS - ng-keypress not working for enter event

Viewed 4833

In my project, ng-keypress is not working for Enter Key from all the places. From some places, it is working perfectly fine but from other places, it is working for all the keys except Enter Key.

Here I'm calling a test() method on the ng-keypress.

<div class="actions">
    <div class="ui approve button red" data-ng-click="test()" id="confirm-yes" tabindex="8" ng-keypress="test()">Yes</div>
    <div class="ui cancel button" data-ng-click="test()" id="confirm-no" tabindex="7" ng-keypress="test()">Cancel</div>
</div>

From test method, I'm just showing the key code. I could see the keycode properly for all other key presses except Enter.

$scope.test = function () { 
            alert('test called'+event.keyCode);
        }

I have gone through many Stack Overflow articles and I'm sure its syntax is correct, but I'm totally confused about its strange behavior.

Any idea why ng-keypress is not working for entering and it is working for all other keys.

4 Answers

it could be because of another handler that invokes event.stopImmediatePropagation(): so far any other handlers are no called

you can check existing handlers for element in browser's Developer tools

You are using same function test() for both ng-click and ng-keypress, try to replace with another function

   <div class="ui approve button red" data-ng-click="test()" id="confirm-yes" tabindex="8" ng-keypress="testcheck()">Yes</div>
    <div class="ui cancel button" data-ng-click="test()" id="confirm-no" tabindex="7" ng-keypress="testcheck()">Cancel</div>

I approached same issue with ngKeypress directive. It's especially interesting that on Angular's official example pressing 'Enter' is recognized.

Solved this problem using ngKeydown directive. It shouldn't make any difference when handling 'Enter' key.

Related