When the enter key is pressed, scope.$watch() does not trigger, and location.path does not function as expected

I've encountered a peculiar problem with AngularJS that I need help with. Here's the situation:

Using scope.watch to monitor text changes in a text field (searchloco).

<input class="typeahead"  ng-model="searchloco" data="{{varu}}" search-bar   type="text"> 

In addition, I'm utilizing a keydown function to detect the Enter key press and I want to change location.Path upon detection.

Strangely enough, when any key other than Enter is pressed, everything works as expected - the text updates in watch, and the keydown function is triggered properly. However, when the Enter key is pressed, the keypress event fires but the watch cycle does not pick up this key. The statement "Location.path("/")" following the if statement meant to confirm an 'Enter' key also fails to execute until another key (a-z) is typed.

 element.on( 'keydown' , function (e){
            console.log("=== key down pressed === ",e);
            if(e.which == 13){
                location.path('/search/');
                 ...
                 ...

If my explanation isn't clear, please let me know how I can provide further clarification on this puzzling issue.

Answer №1

It's recommended to encapsulate your code within a callback function and include $scope.$apply() like this:

element.on('keydown', function (e){
    $scope.$apply(function () {
        console.log("=== key down pressed === ", e);
        if (e.which == 13){
            location.path('/search/');
        }
    });
});

ng-keydown

Alternatively, you can use the Angular directive ng-keydown instead of jQuery-style element.on().

HTML:

<input class="typeahead" ng-keydown="keypress" ng-model="searchloco" data="{{varu}}" search-bar type="text">

JavaScript:

$scope.keypress = function ($event){
     console.log("=== key down pressed === ", $event);
     if ($event.which == 13){
         location.path('/search/');
     }
});

ng-submit

For better cross-platform compatibility, it's best to wrap the input field in a form and utilize ng-submit.

<form ng-submit="go">
    <input class="typeahead" ng-model="searchloco" data="{{varu}}" search-bar type="text">
</form>

JavaScript:

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

Answer №2

Have you experimented with injecting $location into your code and utilizing the line $location.path('/search/');?

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

Decoding JSON data with JavaScript

My JavaScript code is giving me trouble. I am using an ajax method that returns a JSON string like this: { "ObjectResponse": { "Operation": "OK", "Response": "SUCCESS", "Message": "List of AAA Found", "List": [ { "keySourc ...

Analyzing various field data collectively

Is there a way to use jQuery to compare multiple input field values and trigger an alert message saying 'There are similar values' if any match is found? <input value="111"> //similar <input value="222"> <input value="111"> //s ...

Here is a unique version: "In Javascript, users can trigger the function this.Something() from within this.img.onload by

I have some code that looks like this... Thing function () { var img = new Image; DoSomeStuff function() { //Code here that relies on my image being loaded... }; InitMe function(src) { this.img.onLoad = this.DoSomeStuff; ...

creating dynamic column headers with JavaScript

I am looking for a way to make the column names dynamic so that I don't have to manually update them every time. Here is my code snippet: jqGrid11.prototype = { display : function() { $('body').append(this.html.join("")); $("#jqGrid").j ...

Tips for using tooltip.format() to access an array of objects in anychart.js

Having difficulty displaying an array of objects in the tooltip of an Anychart.js map. I know we can access the dataset using %[name of property in data set]. The structure of my dataset is as follows: { "country": "Austria", &q ...

Detect a custom button click event to trigger a re-render of dates in the controller for the AngularJS date picker

I have customized the datepicker popup by adding a custom button inside the <script id="template/datepicker/popup.html" type="text/ng-template"> directive. The custom button is visible in the image below, but I am looking to capture the click event ...

Is it possible to conceal the dates from past months in the datepicker plugin?

Currently, I am utilizing a datepicker tool from jQuery UI and adjusting its CSS to suit my requirements. My goal now is to hide any dates that are not currently active, specifically those displayed from other months. I am unsure if this can be achieved ...

Check if the element is not present in the array, then add it to the array

I am attempting to generate an array in JavaScript with unique elements extracted from a JSON feed. My thought process is possibly too influenced by PHP, where a simple script like the one below would suffice: $uniqueArray = array(); foreach($array as $ke ...

Interactive JavaScript Linkage

Recently, I came across some code that I inherited (definitely not mine!) which uses a session variable in the HTML header to link to a specific javascript file. For example: <SCRIPT language="javascript" src="../JavaScript/<%=Session("jsFileName") ...

Activate trust proxy in Next.js

When working with Express.js, the following code snippet enables trust in proxies: // see https://expressjs.com/en/guide/behind-proxies.html app.set('trust proxy', 1); I am attempting to implement a ratelimit using an Express middleware that is ...

Angular Screen Capture Creator

I am currently in the process of constructing a straightforward Angular screenshot generator utilizing this specific jQuery plugin. Here is the link to my project on Plunker This snippet showcases my index.html file: <!DOCTYPE html> <html ng-ap ...

The mysterious case of the vanishing close button on Curator.io's mobile

Currently, I am using curator.io aggregator to showcase my Instagram feed on the website. An issue arises when switching to mobile view as the close button (class="crt-close") disappears. You can see an example of this here: To replicate the pr ...

Verify record removal without a PHP click

My website features a navigation menu that streamlines the browsing experience: <form action="../"> <select onchange="window.open(this.options[this.selectedIndex].value,'_top')"> <option value="" selected="selected">Navigate< ...

Rendering an Angular HTML page with Koa.js

Recently, I decided to switch from using express to Koa.js for my node.js projects. While in express we typically use the render function to retrieve HTML pages, in Koa.js, things work a bit differently. I attempted to access an Angular HTML page from Ko ...

The tablesort feature is experiencing difficulty sorting tables with dynamically changing content

I have a question about sorting columns in a PHP file that calls a JS file. The PHP file contains two tables with the table sorter plugin implemented, but one of them works and the other doesn't. The working table is populated through an Ajax call, wh ...

Utilizing NextJS to Call the Layout Component Function from the Page Component

I can't seem to find an answer to this question for Next.js after searching online. While there are solutions available for React, I don't think they will work in the Next.js framework. My application is essentially a shop with a navigation menu ...

Jump to Anchor when Page Reloads

Hey there! I'm currently developing a gallery script and I'm trying to figure out how to automatically position the page to the top of a specific anchor when it is loaded. I attempted to use the following code: <script>location.href = "#tr ...

The push() function is triggering an error where db._checkNotDeleted is referenced incorrectly as a

I'm attempting to save an object in the database. Here's the code snippet I've been using: app.post('/newOrderWithObject', (req, res) => { var msg = {"name":"Harry"}; push(ref(db,"test/orders&qu ...

Having trouble executing a fetch request in Next.js

I am struggling to perform a fetch request using getStaticProps in Next.js. Despite following the documentation provided on their website, I am unable to console log the props successfully. My background is mainly in React, so I tried to adapt my approac ...

Running a Python Selenium script

I need some help executing this script using selenium. <div class="vbseo_liked"> <a href="http://www.jamiiforums.com/member.php?u=8355" rel="nofollow">Nyaralego</a> , <a href="http://www.jamiiforums.com/member.php?u=8870" rel="nofollo ...