Search code examples
angularjsangularjs-directiveangular-ui

How to use a keypress event in AngularJS?


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 
}

Solution

  • 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>