AngularJS ng-keydown 指令仅适用于 <input>语境? [英] AngularJS ng-keydown directive only working for <input> context?

查看:25
本文介绍了AngularJS ng-keydown 指令仅适用于 <input>语境?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 AngularJS 还很陌生,但到目前为止我已经很喜欢它了.对于我当前的项目,我需要热键功能,并且很高兴看到自 1.1.2 版本以来它得到支持.

I am pretty new to AngularJS but found it quite to my liking so far. For my current project I need hotkey functionality and was happy to see that it is supported since the 1.1.2 release.

ng-keydown 指令 (http://code.angularjs.org/1.1.3/docs/api/ng.directive:ngKeydown) 对输入类型按预期工作,但在任何其他上下文(如 div 等)中我都失败了.鉴于文档另有说明,这似乎很奇怪.

The ng-keydown directive (http://code.angularjs.org/1.1.3/docs/api/ng.directive:ngKeydown) works as expected for input types but fails me for any other context like div etc. which seems odd given that the documentation says otherwise.

这是一个最小的例子 (http://jsfiddle.net/TdXWW/12/)不工作:

Here is an minimal example (http://jsfiddle.net/TdXWW/12/) of the working respectively the not working:

<input ng-keydown="keypress($event)">
<div ng-keydown="keypress($event)">

注意:我知道这可以用普通的 jQuery 处理(http://www.mkyong.com/jquery/how-to-check-if-an-enter-key-is-pressed-with-jquery/) 但我更喜欢了解如何在 AngularJS 中处理它.

NOTE: I know this could be handled with plain jQuery (http://www.mkyong.com/jquery/how-to-check-if-an-enter-key-is-pressed-with-jquery/) but I much prefer to understand how to deal with it in AngularJS.

推荐答案

我遇到了同样的问题,并且能够按照此评论中提供的这个简单提示进行修复:https://stackoverflow.com/a/1718035/80264

I was having the same problem and was able to fix it by following this simple tip provided in this comment: https://stackoverflow.com/a/1718035/80264

你需要给 div 一个 tabindex,这样它才能获得焦点.

You need to give the div a tabindex so it can receive focus.

<div id="testdiv" tabindex="0"></div>

这篇关于AngularJS ng-keydown 指令仅适用于 &lt;input&gt;语境?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆