Ways to halt a watch statement or digest cycle within Angular

At the moment, I have implemented a text input linked to a model using a $scope.watch statement to observe changes in the model. The purpose of this setup is to create an auto-complete / typeahead feature.

<!-- HTML -->
<input type="text" ng-model="search.mySearchText">


// JS
var deregister = $scope.$watch('search.mySearchText', doSearch);

function doSearch() {
    mySearchService.executeSearch(search.mySearchText)
        .then(function(res) {
            // handle the data
        });
}

Although everything functions as intended, occasionally within the .then function I need to modify the value of search.mySearchText. This, however, triggers the watcher again, which is not desired.

I am looking for a way to prevent the $watch from triggering next time; possibly by indicating to Angular that the watched model property is no longer dirty?

My attempt at removing the $watch by de-/re-registering it during appropriate times did not work successfully.

function doSearch() {
    mySearchService.executeSearch(search.mySearchText)
        .then(function(res) {
            deregister(); // stop watching
            search.mySearchText = 'some new string'; // update the model without triggering another search
            deregister = $scope.$watch('search.mySearchText', doSearch); 

        });
}

Unfortunately, this method did not achieve the expected result of preventing the event from firing, leading me to seek alternate ways to suppress the trigger.

Answer №1

To prevent doSearch from exiting prematurely, you can utilize a variable that controls its behavior:

var searchInProgress = true;
function doSearch() {
    if (!searchInProgress) return;
    mySearchService.executeSearch(search.mySearchText)
        .then(function(res) {
            searchInProgress = false;
            // perform desired operations on search.mySearchText
            searchInProgress = true;
        });
}

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

What exactly does a 'hoisted manifest' mean when it comes to using Yarn?

Encountering an issue while attempting to install a package using yarn, I am receiving the error message: expected hoisted manifest for \"myPackage#@material-ui/core#react-dom\" However, the concept of a 'hoisted manifest' is not entir ...

Revise Bootstrap accordion setup

I currently have a Bootstrap accordion set up on my website using Bootstrap 4.1.0 <div id="accordion" class="mt-3"> <div class="card"> <div class="card-header bg-dark text-white" id="headingOne"> <h5 class="mb-0 f ...

Tips for adding a border to an element when hovered over

I am looking to achieve a hover effect that displays a border around an element without actually adding the border to the element itself, as shown in this image: https://i.sstatic.net/iFpCA.png The challenge I'm facing is that I want to allow users ...

uib-carousel glitching and stuck in never-ending loop

In my HTML, I have the following code snippet: <div style="height: 305px"> <div uib-carousel active="false" interval="50000" no-wrap="true"> <div uib-slide ng-repeat="slide in shoes track by slide._id" index="slide._id"> < ...

Help! My express.js query is not functioning properly

I am facing an issue with a query in express.js. Citta_p and Citta_a are two arrays, and I need my query to return all the IDs for cities. However, it seems that only the last value is being returned, as if my cycle starts from var i = 1 and skips the valu ...

Mobile device scrolling glitch

I'm currently working on my website, which can be found at . After testing it on mobile devices, I came across an issue that I just can't seem to fix. For instance, when viewing the site on a device with 768px width, you can scroll to the righ ...

What are the steps for sorting objects in an array by their data type attribute?

I am currently working with a JavaScript array of people objects that is dynamically rendered from JS. My goal is to implement a filter on the objects based on the selection made in the dropdown menu and matching it with the department attribute specified ...

Issues with XMLHttpRequest functionality

I'm currently working on a project where I need to update the TextArea element in my HTML every 2 seconds dynamically, without reloading the page. The issue I'm facing is that when I use alert(request.readystate), it returns undefined instead of ...

Unable to interpret data from the API

{ id: 8, customerName: "xyz", customerMobileNumber: "123456789", customerBillingAddress: "xyz address", customerShippingAddress: "xyz address", customerProductPurchasedDate: "2021-11-09T09:07:00.000Z", cust ...

AngularJS causing issues with page redirection functionality

Incorporating angularjs routing into my web app has been a big task. I've set up the $locationProvider and included the base tag in the HTML head as <base href="/webapp/"> to get rid of the hash symbol in the URL. It's been smooth sailing w ...

Please ensure the public_id parameter is included and provide the necessary value for the imageId when working with Cloudinary

I am in the process of developing a website where users can share insights and comments on novels they have read. Users have the option to include images of the novel with their posts or not. If an image is included, the post schema requires attributes im ...

Managing extensive geographical information through HTTP

What is the most efficient way to transmit a substantial volume of map information via HTTP for rendering on the client side? There must be a more effective approach than simply transmitting a JSON file containing all map data. I am interested in how maj ...

Enhance jQuery for a dynamic navigation dropdown with multiple sub-menus

Looking for help with a jQuery script as I am a beginner in using jQuery. jQuery(document).ready(function ($) { $(".sub-menu").hide(); $(".current_page_item .sub-menu").slideDown(200);; $("li.menu-item").click(function () { if ($('.sub-menu&apos ...

What methods can be used to reveal the true value of data that has been encrypted?

Is it possible to retrieve the original value of data that has been hashed? Can the hashcode be reversed to reveal the real value of the data? String ida = new String(txtID.getText().toString()); int idb = ida.hashCode(); codeD.setText("result: " + ida) ...

Console log messages not displaying in Express.js app method

const express = require("express"); const app = express(); app.listen(3000, function () { console.log("Server started at port 3000."); }); app.get("/", function (req, res) { console.log("Hello, world"); const truck = "drive"; res.send("Hello, ...

What is the best way to use a button to hide specific divs upon clicking?

Is there a way to use a button onclick event to hide specific divs within a parent div? I've tried using .toggleClass('.AddCSSClassHere') but I'm not sure how to apply it to multiple divs. The jQuery snippet provided only allows me to h ...

"I am trying to figure out how to set a link to an image using JavaScript. Can someone help me

I need help figuring out how to insert an image or gif file within two inverted commas '' in this line of code: _("status").innerHTML = ''; (line number 13 in the actual code) Your assistance with this question would be greatly appreci ...

Easy Steps for Mapping Json Data into an Array

Here is the JSON Format I am working with: { "Data": { "-template": "Parallax", "Explore": { "IslandLife": { "TourismLocation": [ { "Title": "Langkawi", "Latitude": "6.350000", "Longitude": "99.800000", "YouTub ...

Memory Match: Picture Edition

In this memory game, letters are used. I had considered changing it to a picture-based game, but I faced difficulty in generating images and incorporating them into the array. <script> var memory_array = ['A', 'A', 'B&ap ...

JavaScript popup menu with a redirect URL

I utilized Tinybox from this source for launching a popup webpage. I am hoping that when I click the links on the webpage, the popup will close itself and redirect to the link's URL. Here are my JavaScript and HTML codes: <script type="text/java ...