使用 ESC 键清除 Angular/AngularUI 中的输入文本字段 [英] Clear input text field in Angular / AngularUI with ESC key

查看:25
本文介绍了使用 ESC 键清除 Angular/AngularUI 中的输入文本字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Angular 应用程序的几个地方,我需要使用 ESC 键清除用户的输入.问题是,我不知道如何处理文本输入字段(textarea 清除 OK).看到这个小提琴:

In several places of my Angular app I need to clear inputs from user with the ESC key. The problem is, I don't know how to do it with text input fields (textarea is clearing OK). See this fiddle:

jsFiddle 问题演示

绑定:

<input ng-model="search.query" ui-keypress="{esc: 'keyCallback($event)'}" />

我使用的回调:

$scope.keyCallback = function($event) {
  $event.preventDefault();
  $scope.search.query = '';
}

任何人都可以弄清楚我需要做什么才能使用 ESC 键清除文本输入?

解决方案:正如 bmleite 所建议的,您不应该听 'keypress' 而应该听 'keydown''keyup'.问题是,'keydown' 在 Firefox 中不起作用,所以只有 'keyup' 做了监听 ESC 的魔术.;)

SOLUTION: As adviced by bmleite, you shouldn't listen for 'keypress' but for 'keydown' and 'keyup'. Problem was, that 'keydown' does not work in Firefox so only 'keyup' did the magic trick with listening for ESC. ;)

工作小提琴:http://jsfiddle.net/aGpNf/190/

解决方案更新:最后,我不得不同时监听 'keydown' 和 'keyup' 事件.因为在我的情况下,FF 确实将 ESC keydown 上的输入字段重置为以前的状态,所以它弄乱了我的模型.所以keyup"清除模型,keydown"检查模型是否为空并执行适当的操作.我还需要手动散焦输入以防止文本弹出.:/

SOLUTION UPDATE: In the end I had to listen for both 'keydown' and 'keyup' events. Because in my case FF does reset input field on ESC keydown to previous state, so it messed up my model. So 'keyup' clears the model and 'keydown' checks if model is empty and does appropriate action. I also need to manually defocus input to prevent text popping back in. :/

推荐答案

已接受的答案 对 IE 10/11 不起作用.这是一个解决方案基于另一个问题:

The accepted answer does not work for IE 10/11. Here is a solution based on another question that does:

指令

.directive('escKey', function () {
  return function (scope, element, attrs) {
    element.bind('keydown keypress', function (event) {
      if(event.which === 27) { // 27 = esc key
        scope.$apply(function (){
          scope.$eval(attrs.escKey);
        });

        event.preventDefault();
      }
    });
    scope.$on('$destroy', function() {
        element.unbind('keydown keypress')
    })
  };
})

HTML:

<input ... ng-model="filter.abc" esc-key="resetFilter()" >

Ctrl

$scope.resetFilter = function() {
  $scope.filter.abc = null;
};

这篇关于使用 ESC 键清除 Angular/AngularUI 中的输入文本字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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