How to use a keypress event in AngularJS?

Venkata Tata picture Venkata Tata · Jul 4, 2013 · Viewed 473.5k times · Source

I want to catch the enter key press event on the textbox below. To make it more clear I am using a ng-repeat to populate the tbody. Here is the HTML:

<td><input type="number" id="closeqty{{$index}}" class="pagination-right closefield" 
    data-ng-model="closeqtymodel" data-ng-change="change($index)" required placeholder="{{item.closeMeasure}}" /></td>

This is my module:

angular.module('components', ['ngResource']);

I am using a resource to populate the table and my controller code is:

function Ajaxy($scope, $resource) {
//controller which has resource to populate the table 
}

Answer

EpokK picture EpokK · Jul 4, 2013

You need to add a directive, like this:

Javascript:

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

                event.preventDefault();
            }
        });
    };
});

HTML:

<div ng-app="" ng-controller="MainCtrl">
    <input type="text" my-enter="doSomething()">    
</div>