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

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

问题描述

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

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'键" .问题是,"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键按下时的输入字段重置为先前状态,所以使我的模型混乱.因此,"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天全站免登陆