To capture keydown and keypressed events, you can create a custom directive. Below is a tested implementation:
var app = angular.module('app', []);
// Helper service to identify arrow keys from key codes
app.factory('keys', function() {
var keysEnum = { left: 37, up: 38, right: 39, down: 40 };
var theKeys = [keysEnum.left, keysEnum.up, keysEnum.right, keysEnum.down];
function isIn(val) {
var isin = false;
if (theKeys.indexOf(val) >= 0) {
isin = true;
}
return isin;
}
function keyFromCode(code) {
var key = 'unknown';
switch (code) {
case 37:
key = 'left';
break;
case 38:
key = 'up';
break;
case 39:
key = 'right';
break;
case 40:
key = 'down';
break;
}
return key;
}
return {
isIn: isIn,
keyFromCode: keyFromCode
};
});
// Custom directive to detect pressed arrow keys
app.directive('keypressed', ['keys', function(keys) {
return function(scope, element, attrs) {
// Listen for keydown and keypress events
element.bind("keydown keypress", function(event) {
var code = event.which;
// Perform action if an arrow key is pressed
if (keys.isIn(code)) {
console.log(keys.keyFromCode(code));
}
});
};
}]);
Usage of the directive:
<span ng-app="app">
<input keypressed />
</span>
If you're using an HTML template engine, you can implement the directive as follows:
input(keypressed)