Angular - detect backspace key press

I am attempting to detect the backspace key press using ngKeypress, ngKeydown, and ngKeyup, inspired by this question on Stack Overflow.

Below is the HTML code snippet:

<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 here is the 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 tested with ngKeypress, ngKeydown, and ngKeyup, but none of them has been successful.

Full code snippet:

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

})();

Answer №1

Implementing in a Controller

I have provided a clean example of your code which appears to be functioning correctly.

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/


Usage in a directive

If you wish to encapsulate the <input> within a directive, the code below can be utilized:

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/

Answer №2

When using Angular 2+, you have the ability to directly bind the Backspace event to an element using keydown or keyup.

Utilizing Special Modifier Keys and Combinations

This functionality extends to special and modifier keys such as 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)="...">

This functionality also applies to letters, numbers, arrows, and function 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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Modifying webpage design using JavaScript for styling

Is there a way to change the css style(defined in the page source) dynamically with Java? I know it is possible to do it with JavaScript. If there isn't, are there other situations where JavaScript is the only choice developing a web app? ...

Is Eval really as bad as they say... What alternative should I consider using instead?

After making an ajax request, a JSON array filled with user inputs is returned to me. The inputs have already been sanitized, and by utilizing the eval() function, I can easily generate my JavaScript object and update the page... However, there lies a dil ...

Revise shiny datatable to display total column sum differently

This is a follow up question to this inquiry: Adding Total/Subtotal to the bottom of a DataTable in Shiny. Below is the code snippet referenced: library(shiny) library(DT) ui <- shinyUI(fluidPage( h1('Testing TableTools'), mainPanel( ...

Clicking on the image in an owl carousel slider does not trigger the onsen template page to load

I am experiencing an issue with my owl carousel slider while calling an API for page content on image click. I have implemented an onsen template page using ng-click on image, but it only works for the first image click. Subsequent images do not call the o ...

The click event for getelementbyid() function is malfunctioning

I need assistance with a website I am creating that plays audio when a certain condition is met. Specifically, I want the audio to play if x falls within a specific range of numbers, but also continue playing if x does not fall within that range after th ...

Finding the appropriate method to access a template variable reference in a designated row of an Angular Material table (Angular 7)

Currently, I am working on implementing a more intricate version of a behavior inspired by Angular Material's tutorials. In my simplified example, an Angular Material table is populated with data from a string array. The first column contains input fi ...

Creating a structured file hierarchy by extracting files from Amazon S3 and transferring them for storage in Firebase

I am looking to retrieve key/value pairs from Amazon S3 and then store some of the obtained information in Firebase to build a file system in AngularJS. This question focuses only on storing in Firebase. It is essential to be able to create an unlimited ...

When a form input is submitted, the webpage will refresh with a new

I have a form embedded on my WordPress page. I want to identify users without referrers so that I can set the referrer for them automatically (the referrer part is handled by a plugin). The registration form URL looks like this: The code provided below w ...

What could be causing my Next.js application to not function properly on Safari?

With my current project of developing a web app using nextjs, I'm encountering an issue specifically on Safari browser for Mac. Surprisingly, everything works perfectly fine on other browsers and even on iPhone. Upon opening the developer console, thi ...

Right-click context menu not working properly with Internet Explorer

Seeking assistance with extracting the URL and title of a website using JavaScript. The script is stored in a .HTM file accessed through the registry editor at file://C:\Users\lala\script.htm Below is the script: <script type="text/java ...

Obtaining IP Address with Jquery or Phonegap: A Guide for Cross Platform Development

Is there a way to retrieve the IP address using Jquery or Phonegap? I am currently working on an application that is compatible with Android, iPhone, and Windows platforms. I'm in need of a solution to locate the IP address of a request. ...

Is {{@index}} an even or odd number in Handlebars: A Step-by-Step Guide

I'm currently cycling through an array, and I'd like to adjust the background color of the div based on whether the current index is odd or even. Unfortunately, when I try to use {{@index}} within an if statement in Handlebars, like so: {{#each ...

Cannot locate AngularJS + Typescript controller

I'm encountering an error while attempting to integrate TypeScript with AngularJS. The issue I'm facing is: Error: [$controller:ctrlreg] The controller named 'MyController' has not been registered Does anyone have any insights on what ...

Encountering an issue with Server Side Rendering in React Router Dom where an error message pops up saying: "Warning: React.createElement: type is

Specific Error: A warning has occurred: React.createElement: the type provided is invalid -- it was expecting a string (for built-in components) or a class/function (for composite components), but instead received an object. in Posts in Connect(Po ...

angularjs-multiselect-dropdown option angularjs

I am using a dropdown-multiselect component that leverages Bootstrap's Dropdown functionality along with AngularJS directives and data binding. I am new to AngularJS. <li id="bedsLists"> <div ng-dropdown-multiselect="" options="b ...

Is Typescript capable of converting ES6 code to ES5 during transpilation?

Currently, I'm in the process of developing an application utilizing Angular 2 and TypeScript. My goal is to incorporate a JavaScript method, specifically 'filter' for arrays, that is compatible with IE 11+, Chrome 45+, and other similar bro ...

Tasks should be defined prior to being referenced in order to avoid any issues

Utilizing multiple files with gulp@4, the main gulpfile.js includes all other files within the ./tasks/ directory. We have implemented the npm gulp-hub package to incorporate multiple gulpfiles within the ./tasks/ directory. However, upon calling the tasks ...

Storing a collection of objects in session storage

I've been struggling to save an array containing the items in my online shopping cart. Even though both the object and the array are being filled correctly, when I check the sessionStorage, it shows an array with an empty object. I've spent a lot ...

To link the information within the angularJS controller

I've recently generated a div element dynamically within the controller function of my AngularJS application. However, I'm facing an issue where the data is not binding as expected inside this div element. Here is a snippet of my code: function ...

The basic node API request is not showing any information

There is a request in my server.js file var Post = require('./../models/post'); //GET ALL POSTS app.get('/api/posts', function (req, res) { Post.getPosts(function (err, posts) { if(err) { throw err; } ...