Search code examples
htmlangularjskeypress

Detect if key "delete" was pressed with angularJS


Hi I've got follow code:

angular.module("myApp", []).controller("myController", function($scope) {
  $scope.pressedKey = function(keyObj) {
    $scope.myKey = keyObj.key;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myController">
  <input ng-keypress="pressedKey($event)"><br>{{myKey}}
</div>

I use the ng-keypress on an input for detecting if there was a key-event and which key was clicked. I need all numbers and letters and also the enter and delete key. Now, the numbers, letters and the enter works fine, but when I click the delete key, nothing happens. How can I detect it also with angular?

Thanks & cheers.


Solution

  • Use ng-keydown instead of ng-keypress:

    angular.module("myApp", []).controller("myController", function($scope) {
      $scope.pressedKey = function(keyObj) {
        $scope.myKey = keyObj.key;
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    
    <div ng-app="myApp" ng-controller="myController">
      <input ng-keydown="pressedKey($event)"><br>{{myKey}}
    </div>

    You can read more about the difference between keydown and keypress here.