我尝试创建类似于konami代码的交互" up,up,down,down,a,b,a,b,输入" - >事情发生了。
是否可以使用ng-keypress收听箭头按键?它似乎不起作用?
HTML:
input( ng-keypress='changed($event)' )
的js
$scope.changed = (evt) ->
console.log(evt)
这不会退出箭头键事件吗?
我是否必须在窗口上推出自己的听众?如果是这样,我怎么能以角度来实现这个目标?
答案 0 :(得分:21)
$scope.key = function($event){
console.log($event.keyCode);
if ($event.keyCode == 38)
alert("up arrow");
else if ($event.keyCode == 39)
alert("right arrow");
else if ($event.keyCode == 40)
alert("down arrow");
else if ($event.keyCode == 37)
alert("left arrow");
}
修改强>
将其从ng-keypress
更改为ng-keydown.
DEMO
<input ng-keydown="key($event)" />
答案 1 :(得分:1)
您可以使用自定义指令来侦听keydown和keypressed事件。我测试的可能实现如下:
var app = angular.module('app', []);
// a helper service to detect the arrow keys from the 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 the arrow key pressed
app.directive('keypressed', [ 'keys', function (keys) {
return function (scope, element, attrs) {
// listen for the events keydown, keypress
element.bind("keydown keypress", function (event) {
var code = event.which;
// if an arrow key is pressed then do something
if(keys.isIn(code)) {
console.log(keys.keyFromCode(code));
}
});
};
}]);
您可以像这样使用上述指令:
<span ng-app="app">
<input keypressed />
</span>
从您发布的代码中看来,您似乎使用了html模板引擎,因此在您的情况下,您可以使用如下指令:
input( keypressed )