How to Perform an Action on Key Press in Angular JS

Here’s a quick way to perform certain operations on key press in an input field while working with AngularJS. E.g. say you want to prevent non-digits from being accepted in an input field.

<input name='foo' id='foo' ng-model='foo' ng-keypress="isNumber($event)" />

Then in your controller, you can do something like:

$scope.isNumber = function (event) {
    var charCode = (event.which) ? event.which: event.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    return true;

Leave a Reply

Your email address will not be published. Required fields are marked *