Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear input text field in Angular / AngularUI with ESC key

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 demonstration of the problem

Binding:

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

Callback I use:

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

Can anyone, please, figure out what I need to do to clear text input with ESC key?

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. ;)

Working fiddle: http://jsfiddle.net/aGpNf/190/

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. :/

like image 237
Jan Peša Avatar asked Feb 01 '13 13:02

Jan Peša


3 Answers

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

Directive

.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;
};
like image 182
s.Daniel Avatar answered Nov 06 '22 23:11

s.Daniel


I solve this problem like this (Controller as vm Syntax):

HTML

<input ... ng-model="vm.item" ng-keyup="vm.checkEvents($event)">

Controller

...
vm.checkEvents = function ($event) {
    if ($event.keyCode == 27) {
        vm.item = "";   
    }
}
like image 11
Bijan Avatar answered Nov 06 '22 22:11

Bijan


Listen for 'keydown' or 'keyup' events instead of 'keypress':

<input ng-model="search.query" ui-keydown="{esc: 'keyCallback($event)'}" />
like image 9
bmleite Avatar answered Nov 06 '22 22:11

bmleite