anguna anguna - 1 year ago 100
AngularJS Question

Angular, how to hit enter on input to run a function?

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.

Answer Source

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 () {

Then, in the HTML you can do this:

<input type="text" ng-model"whatever" ng-enter"submitAFunction()">        
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download