Angular navigation does not update upon key press

Is it possible to hit the escape key anywhere on the page without focusing on any element like a button or input? This approach fails:

  $(document).keyup(function(e) {
    if (e.keyCode === 27) {
      $location.path("/");
    }
  });

However, this method works:

  $scope.cancelEdit = function() {
      $location.path('/');
  }

Here's the HTML code for the working solution:

<button ng-click="cancelEdit()" type="button" class="btn btn-default">Cancel</button>

UPDATE:

1. The following methods also do not work:

$document.on('keyup', function(e) {.....

$document.bind('keyup', function(e) {....

2. Below is the complete HTML structure:

<div class="edit jumbotron">
  <i id="loader" class="glyphicon glyphicon-refresh"></i>
  <form name="editForm" class="form-horizontal" ng-submit="saveEdit()">
    <div class="panel panel-info">
      <div class="panel-heading">Edit Site Actions</div>
        <table class="edit_table table table-striped">
          <thead>
            <tr>
              <th class="action_name_cell">Action</th>
              <th class="float_cell">Warning Threshold</th>
              <th class="float_cell">Error Threshold</th>
              <th class="toggle_cell">Enabled</th>
            </tr>
          </thead>
          <tbody>
            <tr class="data_row" ng-repeat="row in get_edit_rows()">
              <td class="action_name_cell">{{row.action_name}}</td>
              <td class="float_cell">
                <div class="form-group">
                  <div class="col-sm-8">
                  <input type="number" class="form-control" ng-model="row.warning"
                         name="{{row.threshold_id}}_warning"
                         placeholder="10.0" ng-value="row.warning"
                         ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/"
                         step="0.1" required />
                  </div>
                </div>
              </td>
              <td class="float_cell">
                <div class="form-group">
                  <div class="col-sm-8">
                  <input type="number" class="form-control" ng-model="row.error"
                         name="{{row.threshold_id}}_error"
                         placeholder="10.0" ng-value="row.error"
                         ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/"
                         step="0.1" required />
                  </div>
                </div>
              </td>
              <td class="toggle_cell">
                <label></label>
                <toggle ng-model="row.enabled" name="{{row.threshold_id}}_enabled"
                        ng-true-value="'on'" ng-false-value="'off'"></toggle>
              </td>
            </tr>
          </tbody>
        </table>
    </div>
    <!-- END panel / panel-info -->

    <!-- Buttons -->
    <div class="base_button_wrapper">
      <button type="submit" class="btn btn-success">Save</button>
      <button ng-click="cancelEdit()" type="button" class="btn btn-default">Cancel</button>
    </div>
  </form>
</div>

Answer №1

Don't stick to the old way:

$document.bind('keyup', function(e) {
  if (e.keyCode === 27) {
    $timeout(function () {
      $location.path("/");
    });
  }
});

Go for the $document service :

$(document).keyup(function(e) {
  if (e.keyCode === 27) {
    $location.path("/");
  }
});

UNIQUE LINK

Remember: Clean up your event using $document.unbind('keyup') in $scope.$on('$destroy', ...); to prevent memory leaks.

Answer №2

To handle key events on elements, simply add the following directive:

ng-keyup="cancelEditEscape($event)"
$scope.cancelEditEscape = function(e) {

        if (e.keyCode === 27) {
          $location.path("/");
        }
};

For example:

<div ng-keyup="cancelEditEscape($event)">
     <!-- other HTML content -->
     <button ng-click="cancelEdit()" type="button" class="btn btn-default">Cancel</button>
</div>

Check out this Plnkr for a working example

Update: You can also include the directive in your HTML like so:

<div class="edit jumbotron" ng-keyup="cancelEditEscape($event)">
or within a form tag:
<form ng-keyup="cancelEditEscape($event)">

Answer №3

It is highly likely that the issue arises from a mix of jQuery and angular code, especially since the jQuery event may not be within the angular scope. If you are still utilizing angular 1.x, try using ngKeyUp instead, as it should work correctly: refer to the documentation.

Here's an example (not verified):

<button ng-keyup="cancelEdit()" type="button" class="btn btn-default">Cancel</button>

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

Set maximum size for background image in div

I'm facing some challenges with setting the maximum height of a background image within a div. I want the max height to be equal to the actual height of the image, without stretching it. Ideally, if there is excess content in the div, it should stop a ...

Combining jQuery dataTables and Codeigniter for dynamic rendering using sAjaxSource

I am currently facing an issue while working with dataTables in Codeigniter. I keep encountering the following error message: array_push() expects parameter 1 to be array, null given The resulting output is {"aaData":null} My desired outcome should look ...

Create and transmit an array of JSON objects

I need help with defining and sending a JSON object array. While I've managed to define a single JSON object, convert it into a string, and send it, I'm stuck on how to do the same for an array of objects. It seems like there might be a simple so ...

Use JavaScript or jQuery to calculate the total value of selected radio buttons and display it in the corresponding textbox

I'm looking to calculate the sum of values from radio buttons and display that sum in the corresponding textbox using either JavaScript or jQuery. Each radio button should have a unique class name for its results. So far, I've only managed to ...

Discover the URLs that are connected to my iframe/widget

I've crafted a widget.html page that includes a "Powered by Example.com" box or widget. Additionally, I've implemented an HTML iframe that points to this specific page (widget.html) on my website. <iframe src="http://example.com/widget.html"& ...

Backend framework

Currently, I am in the process of developing a robust web application that heavily relies on JavaScript and jQuery, with ajax functionality included. Additionally, there will be a database in place, managed using mySQL with several tables. I'm undeci ...

Element enclosed within a territory of mongoose Schema

In the midst of developing an API that provides detailed information about laptops, I am utilizing Node.js and MongoDB with Mongoose. The schema I am working with is as follows: const productSchema = mongoose.Schema( { name: { type: String, ...

Binding hover and load events using jQuery on elements that are dynamically generated

One should note that the click event can be successfully bound to an element with the class name keybox, even if this element is dynamically generated. The code for this would look like: $('body').on('click', '.keybox', funct ...

Enhancing visuals with THREE.js and the power of transparency through EffectComposer

I am attempting to blend texture passes in a way that preserves the alpha channel. I have experimented with several methods to achieve this. The renderer has the alpha property set to true. Renderer with various setClearColor settings. The material on th ...

Formatting in Cx framework: Configuring right alignment and decimal precision on NumberField

Currently, I am involved in a project that involves UI development using Cx, a new FrontEnd framework based on React. You can find more information about Cx at One of the tasks in my project involves creating a Grid with filter fields located at the top ...

What strategies can I use to keep my Google Places API key secure within the index.html of my React application?

I'm working with a mern stack and I have a payment page. I'm looking to incorporate the Google Places API for an address auto-complete feature in my form. I have the basic form structure in place, but I'm unsure of how to properly add the ne ...

Which is better for creating a gradual moving background: Javascript or CSS?

I'm attempting to discover how to create a background image that scrolls at a slower pace than the page contents. I'm currently unsure of how to achieve this effect. A great example of what I'm aiming for can be seen here Would this require ...

What is the best way to show the current date and time in an Angular template while ensuring it stays up to

I'm looking to showcase the current date and time in my angular template, and have it automatically refresh when the time changes. The desired application LOOKS as follows: This snippet is from my .html template: <div class="top-right pull-right ...

Embracing the power of mixins in Vue.js

Currently in the process of learning app development with Vuejs. In my main.js file, I have the code for setting up Vue.js. Recently, I created a new directory called /mixins and added a file named api.js. My intention is to use this as a mixin so that eve ...

calls to res.send and res.render

I'm currently trying to determine if it's possible to use res.send(data) and res.render('reports') simultaneously in my code. To provide more details, when I navigate to '/reports', on the server side I am executing a REST ca ...

Switch out everything except for the initial one

Can all instances be replaced except for the first one? For example, 123.45.67..89.0 should turn into 123.4567890. Edit: Specifically seeking a regex solution. I am aware of how to achieve it through concatenation or using the index. ...

Secure your API access with ADFS integration in Angular.js

I am currently working on creating a new feature-rich application and I'm encountering some challenges with designing the authentication process. I have two main requirements: An API must be accessible ADFS must be used for authentication Initiall ...

Failure to execute the success function

My current issue involves making an AJAX call to retrieve a record from the database. Despite console logs showing that the record is successfully returned, the success function fails to execute. function ajaxForParent() { var search = document.getEle ...

Changing states in next.js is not accomplished by using setState

Struggling to update the page number using setCurrentPage(page) - clicking the button doesn't trigger any state change. Tried various methods without success. Manually modified the number in useState(1) and confirmed that the page did switch. import ...

"Adding an active class to a link based on the current page and locale: A step-by-step

Looking to add an active class to the subheader menu on the active page, but facing issues when changing the locale in the link. While it works for links like my-site/my-page, it doesn't work for links like my-site/fr/my-page. Utilizing Storyblok head ...