Reputation: 81
I would like to use ng-keypress
for a div
. But the following is not working:
Html:
<div ng-keypress="myFunction($event)></div>.
Javascript:
$scope.myFunction = function(keyEvent) {
if (keyEvent.which === 13)
alert('I am an alert');
}
Upvotes: 2
Views: 4088
Reputation: 21609
I know its been a long time, but I have no issue getting a key press on a div
. Provided the div
has focus. Its the tabindex="0"
attribute that allows it to receive focus and thus key press events.
In this example, you must first click on (or tab to if you want) the div
before keys are received. You could easily do this programatically in your code.
example code
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.js"></script>
<style>
.box {
background-color: blue;
width: 500px;
height: 500px;
}
</style>
</head>
<body ng-app='app' ng-controller="ctrl">
<div class="box" ng-keypress="key($event)" tabindex="0"></div>
</body>
<script>
angular
.module('app', [])
.controller('ctrl', ['$scope', function($scope){
$scope.key = ($event) => {
console.log('got key ' + $event.code);
}
}]);
</script>
</html>
You don't get all keys with ng-keypress
(e.g arrow keys), but if you use ng-keydown
you do get those keys too.
Upvotes: 0