如何在 AngularJS 中检测 onKeyUp? [英] How can I detect onKeyUp in AngularJS?

查看:28
本文介绍了如何在 AngularJS 中检测 onKeyUp?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 AngularJS 中检测 onKeyUp?

How can I detect onKeyUp in AngularJS?

我正在寻找类似于 ngChange 的ngOnkeyup"指令,但我找不到任何合适的指令.

I'm looking for an 'ngOnkeyup' directive, similar to ngChange, but I can't find anything suitable.

如果没有这样的指令,是否有一种干净的方法可以从浏览器原生的 onkeyup 事件调用控制器?

If there isn't such a directive, is there a clean way to call into the controller from a browser-native onkeyup event?

推荐答案

请参阅下面来自 maklemenz 的第二个答案,它指的是新的内置 ng-keyup 指令

您可以使用 angular-ui 库:

有了angular-ui,你就可以了

With angular-ui, you can just do

<input ui-event="{keyup: 'myFn($event)'}"

如果您不想使用其他库,最有效和最简单的方法是:

If you don't want to use another library, the most efficient and simple way to do this is:

JS

myApp.directive('onKeyup', function() {
  return function(scope, elm, attrs) {
    elm.bind("keyup", function() {
      scope.$apply(attrs.onKeyup);
    });
  };
});

HTML:

<input on-keyup="count = count + 1">

<小时>

编辑:如果您想检测按下了哪个键,您实际上有两个基本选项.您可以向指令添加一个属性来处理指令中允许的键,或者您可以将按下的键传递给您的控制器.我通常会推荐指令处理关键方法.


Edit: If you wanted to detect which key was pressed, you have two basic options really. You could add an attribute to the directive to handle the allowed keys within the directive, or you could pass the key pressed to your controller. I would generally recommend the directive handles the key method.

以下是两种方式的示例:http://jsfiddle.net/bYUa3/2

Here's an example of both ways: http://jsfiddle.net/bYUa3/2

这篇关于如何在 AngularJS 中检测 onKeyUp?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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