Can the ng-keypress listen for arrow key presses?

I'm looking to implement a functionality similar to the konami code "up, up, down, down, a, b, a, b, enter" -> triggering an action.

Is it feasible to detect arrow key presses using ng-keypress in AngularJS? It doesn't seem to be working as expected?

html:

input( ng-keypress='changed($event)' )

Js

$scope.changed = (evt) ->
    console.log(evt)

Why are arrow key events not being logged with this function?

Do I need to manually set up event listeners on the window object? If so, how can I achieve this within AngularJS?

Answer №1

CLICK HERE FOR DEMO

$scope.key = function($event){
    console.log($event.keyCode);
    if ($event.keyCode == 38)
        alert("up arrow");
    else if ($event.keyCode == 39)
        alert("right arrow");
    else if ($event.keyCode == 40)
        alert("down arrow");
    else if ($event.keyCode == 37)
        alert("left arrow");
}

MODIFY

Update from ng-keypress to ng-keydown. SEE THE CHANGES HERE

<input ng-keydown="key($event)" />

Answer №2

To capture keydown and keypressed events, you can create a custom directive. Below is a tested implementation:

var app = angular.module('app', []);

// Helper service to identify arrow keys from key codes
app.factory('keys', function() {
    var keysEnum = { left: 37, up: 38, right: 39, down: 40 };
    var theKeys = [keysEnum.left, keysEnum.up, keysEnum.right, keysEnum.down];
    
    function isIn(val) {
        var isin = false;
        if (theKeys.indexOf(val) >= 0) {
            isin = true;
        }
        return isin;
    }

    function keyFromCode(code) {
        var key = 'unknown';
        switch (code) {
            case 37:
                key = 'left';
                break;
            case 38:
                key = 'up';
                break;
            case 39:
                key = 'right';
                break;
            case 40:
                key = 'down';
                break;
        }
        return key;
    }

    return {
        isIn: isIn,
        keyFromCode: keyFromCode
    };
});

// Custom directive to detect pressed arrow keys
app.directive('keypressed', ['keys', function(keys) {
    return function(scope, element, attrs) {
        // Listen for keydown and keypress events
        element.bind("keydown keypress", function(event) {
            var code = event.which;
            // Perform action if an arrow key is pressed
            if (keys.isIn(code)) {
                console.log(keys.keyFromCode(code));
            }
        });
    };
}]);

Usage of the directive:

<span ng-app="app">
    <input keypressed />
</span>

If you're using an HTML template engine, you can implement the directive as follows:

input(keypressed)

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

Utilizing Omit for the exclusion of nested properties within a TypeScript interface

One of the components in a library I am using is defined like this: export interface LogoBoxProps { img: React.ReactElement<HTMLImageElement>, srText?: string, href?: LinkProps['href'] } export type LogoBoxType = React.FC<React.HT ...

Exploring the Module System of TypeScript

I am working with a TypeScript module structured like this: let function test(){ //... } export default test; My goal is for tsc to compile it in the following way: let function test(){ //... } module.exports = test; However, upon compilation, ...

What is the best way to toggle a d3 svg overlay using a leaflet layer control?

I am looking for a solution to place 3 d3 svgs on a leaflet map and control them as easily as leaflet layers. Check out this code example, which works but is not ideal. The key part is from line 75 onwards, where I create a custom layer control linked to ...

Changing the color of an open Bootstrap 4 accordion panel when the page loads

I am looking to emphasize the panel that the user has opened. If a user clicks the button in the card header, the background turns red, which is working smoothly as demonstrated in the code snippet. In certain scenarios, the first panel is open by default ...

Trying to set headers in Node/Express after they have already been sent is causing an error

I am attempting to send form data from the client side using jQuery to a POST route that will then pass the data to an API in Node/Express. I am encountering an issue where I receive the error message "Can't set headers after they are sent" and I am ...

Creating a diagonal effect on a table using jQuery

I am interested in adding a diagonal effect to my table. For instance, if I have a 5x5 table, I want to highlight the first row and set the background color of the corresponding column in that row to red. The same should be done for each subsequent row. ...

The webpack vue-loader throws an error message stating "unexpected token {" when processing a single-page .vue component

As a C# backend developer, I am venturing into the world of Vue.js. I typically work with Visual Studio 2017 + ASP.NET MVC (using it as an API + one layout) + Vue.js + Webpack. .vue single-page component files are loaded by vue-loader, while .js files a ...

How to display two elements side by side within a div using React

I have an array that looks like this: const arr = [1,2,3,4,5,6,7,8,9,10] I am looking to display the elements in pairs per line within two-dimensional divs. Here is what I have in mind: This represents the main React element: render() { return <di ...

Obtain the name of the checkbox that has been selected

I'm new to JavaScript and HTML, so my question might seem silly to you, but I'm stuck on it. I'm trying to get the name of the selected checkbox. Here's the code I've been working with: <br> <% for(var i = 0; i < ...

What inspired the Angular JS Team to name their end-to-end testing tool Protractor?

Have you ever wondered why the name "protractor" was chosen for the end-to-end testing tool in AngularJS? ...

The backend is not receiving the variable through RESTful communication

I'm attempting to pass the word "hello" to the backend of my code using the URL. However, instead of sending the string "hello" to my Java backend code, it's sending an empty string. Below is my backend code: @GET @Path("getJob/{stepName}") @Pr ...

Create a form in a React component that allows the user to input information

My challenge is to create a functionality where each time the add button is clicked, it should dynamically add an input field that I can save. It's similar to this example, but with inputs instead. The complexity arises from the fact that the inputs a ...

Failure to display masonry arrangement

I am working on creating a stunning masonry layout for my webpage using some beautiful images. Take a look at the code snippet below: CSS <style> .masonryImage{float:left;} </style> JavaScript <script src="ht ...

switch between showing and hiding dynamic table rows

As I dynamically add rows to a table, each row can either be a parent row or a child row. My goal is to toggle the visibility of child rows when the parent row is clicked. if (response != null && response != "") { ...

Update the displayed locations on Google Maps by fetching and displaying marker data

I am able to retrieve and display information from my MySQL table, but I need assistance with refreshing this data every 5 seconds using my current code. The data being shown is not extensive, just about 5 or 8 markers at a time. Below is the code I curren ...

How to inject a variable into an AngularJS service that utilizes both $http and $interval functions?

Struggling with $http and $interval, I stumbled upon this code. http://embed.plnkr.co/fSIm8B/script.js I forked it here: http://plnkr.co/edit/Al8veEgvESYA0rhKLn1q To make it more functional, how can I pass a variable to the service? Here is the broken ...

The removeEventListener method in JavaScript fails to function properly

On my website, I have a unique feature where clicking an image will display it in a lightbox. Upon the second click, the mouse movement is tracked to move the image accordingly. This functionality is working as intended, but now I'm faced with the cha ...

How to disable scrolling for React components with CSS styling

When incorporating a React component into my HTML, I follow this pattern: <html> <body> <div id=app>${appHtml}</div> <script src="/bundle.js"></script> </body> </html> Within my application, th ...

What could be the reason why the navbar ul li a instance is not appearing in Bootstrap 4 modal when using an

Can anyone help me solve the issue I'm having with viewing HTML in a Bootstrap 4 modal? Everything shows up except for the navbar ul li a elements. I've searched for a solution everywhere, but haven't found one yet. Please assist! (I want t ...

Distinguishing between {{::somevalue}} and {{somevalue}} in AngularJSIs there a

Hey everyone, I'm currently working on a project where I've come across two different syntaxes for data binding: {{::somevalue}} and {{somevalue}}. I'm not sure about the purpose of each one and couldn't find any information about it on ...