'angular - catch backspace press

I am trying to catch backspace press via ngKeypress, ngKeydown and ngKeyup,follwing How can I detect keydown or keypress question.

Here is my HTML:

<input 
       name="inputText" 
       type="text" 
       class="{{schema.class.control_part_class}} form-control" 
       data-ng-model="data[schema.model]"
       ng-keydown = "changeInput($event)">
</input>

And directive link function:

scope.changeInput = function(e){       
     $log.log('scope', scope); //scope
     $log.log('cont', controller); //controller
     $log.log(e); //works for any other key
     if(e.keyCode === 8){
         //keycode for backspace
         $log.log('backspace') 
     }     
};

I have tried replacing between ngKeypress, ngKeydown and ngKeyup and none of them work.

Entire code: html

<div form-field-injector schema="vm.schema" data="vm.data">
                <span class="star-color-red" ng-show="schema.validation.required">*</span>
                <label class="{{schema.class.label_part_class}} label-control">{{::schema.name}}
                </label>
                <input 
                    name="inputText" 
                    type="text" 
                    class="{{schema.class.control_part_class}} form-control" 
                    data-ng-model="data[schema.model]"
                    data-ng-model-options="{ debounce: 300 }" 
                    data-ng-disabled="{{::schema.disabled}}"
                    ng-keydown = "changeInput($event)"></input>

directive:

(function () {
    'use strict';

    function IsrTextField($log, $compile, $templateRequest) {
        $log = $log.getInstance('IsrTextField.directive', true);
        $log.debug("load()");

        var _templateUrl = 'common/directives/isr-text-field/templates/isr.text.field.tpl.html';
        var _inputElement = null;

        function _link(scope, iElem, iAttrs, controller) {   
            $log.log('scope input', scope);
            function _onBlur() {
                $log.debug("_onBlur()");
                controller.eventRunner(controller.schema.events.on_blur.action, {
                    item: controller.schema.events.on_blur.args
                });
            }
            scope.changeInput = function(e){
                 $log.log('scope', scope); //scope
                 $log.log('cont', controller); //controller
                 $log.log(e); //works for any other key
                 if(e.keyCode === 8){
                    //keycode for backspace
                    $log.log('backspace') 
                 }
             };


            //1. request template from server
            // Load the html through $templateRequest
            $templateRequest(_templateUrl)
                .then(function success(html) {
                    // Convert the html to an actual DOM node
                    var template = angular.element(html);
                    // Append it to the directive element
                    iElem.append(template);

                    // 1. get input element from template
                    _inputElement = $('.form-control', iElem);
                    if (!_inputElement) {
                        $log.warn("there is no .form-control element class");
                        return;
                    }

                    // set template attributes from schema (before compile)
                    if (controller.schema.modelOptions) {
                        _inputElement.attr("data-ng-model-options", controller.schema.modelOptions);
                    }

                    // set events/bind from schema
                    if (controller.schema.events && controller.schema.events.on_blur) {
                        if (controller.schema.events.on_blur.action) {
                            _inputElement.on('blur', _onBlur);
                        }
                    }

                    // And let Angular $compile it
                    $compile(template)(scope);
                }, function failure(error){
                    $log.error(error);
                });

            // cleanup
            scope.$on('$destroy',
                function destroy() {
                    $log.debug("destroy()");
                    if (_inputElement) {
                        _inputElement.off('blur', _onBlur);
                        _inputElement = null;
                    }
                });

        }

        var directive = {
            restrict: 'EA',
            scope: {
                schema: '=',
                data: '='
            },
            controller: 'isrTextFieldController',
            controllerAs: 'vm',
            bindToController: true,
            link: _link
        };

        return directive;

    }

    angular
        .module('common')
        .directive('isrTextField', IsrTextField);

})();


Solution 1:[1]

In a Controller

I wrote a clean example of your code and it seems to work.

JavaScript:

angular.module('myApp', [])
  .controller('TestController', TestController);

function TestController($scope, $log) {
  $scope.changeInput = function(e) {
    $log.log('scope', $scope); //scope
    $log.log(e); //works for any other key
    if (e.keyCode === 8) {
      //keycode for backspace
      $log.log('backspace');
    }
  };
}

HTML:

<div ng-controller="TestController as test">
  <input name="inputText"
         type="text"
         ng-keyup="changeInput($event)">
</div>

JSFiddle: http://jsfiddle.net/wcws0ubm/1/


In a directive

If you want to encapsulate the <input> into a directive, you can use the following code:

HTML:

<div ng-controller="TestController as test">
  <test-element></test-element>
</div>

JavaScript:

angular.module('myApp', [])
  .controller('TestController', ['$log', TestController])
  .directive('testElement', ['$log', testElement]);

function TestController($log) {
  $log.log("Controller loaded");
}

function testElement($log) {
  return {
    restrict: 'E',
    template: '<input name="inputText" type="text" ng-keyup="changeInput($event)">',
    link: function(scope) {
      scope.changeInput = function(e) {
        $log.log('scope', scope); //scope
        $log.log(e); //works for any other key
        if(e.keyCode === 8) {
          //keycode for backspace
          $log.log('backspace');
        }
      }
    }
  };
}

JSFiddle: http://jsfiddle.net/wcws0ubm/3/

Solution 2:[2]

With Angular 2+ you can bind the Backspace event directly on the element with keydown/keyup.

Using Special Modifier Keys and Combinations

This feature works for special and modifier keys like Enter, Esc, Shift, Alt, Tab, Backspace, and Cmd:

Key(s) Key Name
Enter <input (keydown.enter)="...">
Esc <input (keydown.esc)="...">
Shift <input (keydown.shift)="...">
Alt <input (keydown.alt)="...">
Tab <input (keydown.tab)="...">
Backspace <input (keydown.backspace)="...">
Ctrl <input (keydown.control)="...">
Cmd <input (keydown.meta)="...">

But it also works for letters, numbers, arrows, and functional keys (F1 through F12):

Key(s) Key Name
A <input (keydown.a)="...">
9 <input (keydown.9)="...">
? <input (keydown.arrowup)="...">
F4 <input (keydown.f4)="...">

Source: https://www.digitalocean.com/community/tutorials/angular-binding-keyup-keydown-events

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2 Pierre