Clear input text field in Angular / AngularUI with ESC key

All we need is an easy explanation of the problem, so here it is.

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

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

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;
};

Method 2

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 = "";   
    }
}

Method 3

Listen for ‘keydown’ or ‘keyup’ events instead of ‘keypress’:

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

Method 4

For now, with Angular v4, this works: (keyup.esc)="callback()"

Method 5

I’ve managed to build a directive clearing directly ng-model of the input element and properly working also in Firefox. For that I need to check whether the value is already cleared (modelGetter(scope)) and also wrap the assignment to the zero $timeout method (to apply it in next digest call).

mod.directive('escClear', ['$timeout', '$parse', function($timeout, $parse) {
  return {
    link : function(scope, element, attributes, ctrl) {
      var modelGetter = $parse(attributes.ngModel);
      element.bind('keydown', function(e) {
        if (e.keyCode === $.ui.keyCode.ESCAPE && modelGetter(scope)) {
          $timeout(function() {
            scope.$apply(function () {modelGetter.assign(scope, '');});
          }, 0);
        }
      });
    }
  };
}]);

My $ property is jQuery, feel free to replace it with magic number 27.

Method 6

Angular 2 version which also updates ngModel

Directive

import { Directive, Output, EventEmitter, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: '[escapeInput]'
})
export class escapeInput {

  @Output() ngModelChange: EventEmitter<any> = new EventEmitter();
  private element: HTMLElement;
  private KEY_ESCAPE: number = 27;

  constructor(private elementRef: ElementRef) {
    this.element = elementRef.nativeElement;
  }

  @HostListener('keyup', ['$event']) onKeyDown(event) {
    if (event.keyCode == this.KEY_ESCAPE) {
      event.target.value = '';
      this.ngModelChange.emit(event.target.value);
    }
  }

}

Usage

<input escapeInput class="form-control" [(ngModel)]="modelValue" type="text" />

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply