7

I'm trying to figure out a good way in Angular to run a function by hitting enter from an input in a form. I found this on a stackoverflow post:

    $(".input1").keyup(function (e) {
        if (e.keyCode == 13) {
            // Do something
        }
    });

but I'm wondering if there is a better way to do it.

  • 1
    http://stackoverflow.com/questions/17470790/how-to-use-a-keypress-event-in-angularjs – chf Jul 07 '16 at 16:14

2 Answers2

9

I use a directive like this:

.directive('ngEnter', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if (event.which === 13) {
                scope.$apply(function () {
                    scope.$eval(attrs.ngEnter);
                });
                event.preventDefault();
            }
        });
    };
});

Then, in the HTML you can do this:

<input type="text" ng-model"whatever" ng-enter"submitAFunction()">        
Jaromjj
  • 326
  • 3
  • 17
6

Why not using ng-submit ?

<form ng-submit="myfunction()">
    <input ng-model="myvalue" type="text">
    <input type="submit" value="submit">
<form>

it will execute whatever function is on ng-submit whenever you either click the button, or press enter.

https://docs.angularjs.org/api/ng/directive/ngSubmit

you can see in the example that you can just press enter.

also the submit input can be optional

Sami Triki
  • 408
  • 3
  • 7