ali ali - 1 year ago 335
AngularJS Question

Submit form on pressing Enter with AngularJS

In this particular case, what options do I have to make these inputs call a function when I press Enter?

// HTML view //
<input type="text" ng-model="name" <!-- Press ENTER and call myFunc --> />
<br />
<input type="text" ng-model="email" <!-- Press ENTER and call myFunc --> />

// Controller //
.controller('mycontroller', ['$scope',function($scope) {
$ = '';
$ = '';
// Function to be called when pressing ENTER
$scope.myFunc = function() {

Answer Source

Angular supports this out of the box. Have you tried ngSubmit on your form element?

<form ng-submit="myFunc()" ng-controller="mycontroller">
   <input type="text" ng-model="name" />
    <br />
    <input type="text" ng-model="email" />

EDIT: Per the comment regarding the submit button, see Submitting a form by pressing enter without a submit button which gives the solution of:

<input type="submit" style="position: absolute; left: -9999px; width: 1px; height: 1px;"/>

If you don't like the hidden submit button solution, you'll need to bind a controller function to the Enter keypress or keyup event. This normally requires a custom directive, but the AngularUI library has a nice keypress solution set up already. See

After adding the angularUI lib, your code would be something like:

<form ui-keypress="{13:'myFunc($event)'}">
  ... input fields ...

or you can bind the enter keypress to each individual field.

Also, see this SO questions for creating a simple keypres directive: How can I detect onKeyUp in AngularJS?

EDIT (2014-08-28): At the time this answer was written, ng-keypress/ng-keyup/ng-keydown did not exist as native directives in AngularJS. In the comments below @darlan-alves has a pretty good solution with:

<input ng-keyup="$event.keyCode == 13 && myFunc()"... />

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download