Prevent ng-click action on hitting enter

logo-angularjs

I was doing a functionality in the project I’m currently working, I captured the onKeypress event to capture the enter key when the user finish editing in a form, I also had a button to do another action with an ng-click directive, something like this code:

 

Try This:

I’m currently writing a post about it because I thought it was a bug in the angular core functionality or some code I had written in other place within the application(it wasn’t, I’ll explain later), and it was affecting then my functionality. I was trying to figured out by myself before I search for this problem in internet.

 

book

Book Tip

ng-book – The Complete Book on AngularJS
Ready to master AngularJS? What if you could master the entire framework – with solid foundations – in less time without beating your head against a wall?


Amazon

 

The first thing that came to my mind was to do a directive to capture the enter key in the button and dismiss it

.directive('preventEnterFireing', function() {
            return {
                link: function(scope, element, attrs) {
                    element.keypress(function(e) {
                        if (e.keyCode == 13) {
                            e.preventDefault();
                            return;
                        }
                    });
                }
            }
    });

HTML

<button ng-click="action()" prevent-enter-fireing>Perform action</button>

This doesn’t work!!!! As a matter of fact even if it works, it is a super ugly solution, and doesn’t attack the root of the problem, so I decided to search in internet, and here is the simple but not trivial solution:

The solution:
Your button needs a type=”button”. By default it is type=”submit” which is why it is being called as the form submits when you hit the enter key.

Try This: