How does AngularJS watcher behave when a callback is triggered during a reload or router change?

Can anyone explain why the watch callback is triggered upon browser reload or Angular route change even when the old value and new value are the same? Here's an example:

$scope.test = "blah"; 
$scope.watch("test", function(new, old){
  console.log(new === old);
} 

Every time you reload the page or change routes away and back to that controller, the console log will show true. I had to add a guard inside the callback to prevent unnecessary callbacks. Did I make a mistake somewhere?

Answer №1

If you take a look at the documentation page here, you can find information about when this particular event occurs. The timing may vary based on how your application is structured, but a simple comparison using === will indicate whether there has been a change or not (as recommended).

Answer №2

I want to express my gratitude towards Mathew Berg for providing the solution I needed. By referring to the documentation, I was able to find the answer.

Upon registering a watcher with the scope, the listener function is executed asynchronously (via $evalAsync) to set up the watcher. In some rare instances, this may not be ideal as the listener gets triggered even when the watchExpression's result remains unchanged. To identify and handle this particular scenario within the listener function, one can compare the newVal and oldVal. If these two values are exactly identical (===), it indicates that the listener was invoked solely during initialization.

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

Utilize array collections across various pages for increased efficiency

Currently, I am working with two pages - page1.php and page2.php. Each page has its own controller that handles specific functions. However, there are tabs within both pages that share the same functionality of obtaining a promise from a factory within the ...

Using ServiceWorker with React and Typescript

If you are working on a javascript-based React project, adding a Service Worker is simply a matter of updating serviceWorker.unregister() to serviceWorker.register() in index.jsx. Here is an example project structure: - src |- index.jsx |- serviceWo ...

Issue with jqLite's .triggerHandler() functionality not behaving as anticipated

I'm having an issue with a piece of code that uses triggerHandler. The event is being called correctly, but it's not working as expected. Below is the code snippet and a link to a jsFiddle : HTML: <body ng-app="app"> <button box-cr ...

Retrieving decimal value from a given string

Currently, I am working with Google Maps and encountering an issue with distance values being returned as strings like 1,230.6 km. My goal is to extract the floating number 1230.6 from this string. Below is my attempted solution: var t = '1,234.04 km ...

Addressing Memory Leakage Issues in a Basic Node.js Application

Out of sheer curiosity and as an experiment with NodeJS, I decided to write a basic program to test the Collatz Conjecture for an incredibly high number of integers. While this concept should work fine in theory, my simple code is unexpectedly facing a mem ...

refresh the localstorage array using vanilla JavaScript

I am attempting to remove an element from an array stored in local storage. I am using vanilla JavaScript within a Vue.js 3 component. Here is my array: ["96", "281", "287", "415", "650", "661", & ...

How can the value of a button be displayed in an input box using an onclick function?

When the button '1' is clicked, it displays the value "1" inside a <!p> tag. However, the second button '2' does not display the value "2" in the input box. Even though both functions are identical. //Function with working func ...

How can we deliver pure JS, HTML, and CSS content without relying on static HTML pages?

Looking to create a fast app prototype without using React or Vue? I'd like to avoid simply making an html and js file imported within it. Can npm packages, SCSS be used while programming vanilla Javascript minus a framework? ...

Tips on integrating TypeScript into JavaScript

Currently, I am working with a node.js server.js file. var http = require('http'); var port = process.env.port || 1337; http.createServer(function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res ...

Difficulties encountered when adjusting the size or reducing the images in a Cycle2 slideshow

Greetings to all fellow coders! Thank you for taking the time to read this post. I am currently facing a challenge in my web development project where I am trying to make my Cycle 2 slideshow images resize and reposition alongside other divs when the wind ...

Learn the secrets of displaying a pop-up alert message seamlessly without interrupting the page's rendering process. Additionally, discover how to effortlessly refresh a chart every

I need to display a pop-up if the value is less than 3. I have tried using the alert function, but it causes the page to not render. How can I show the pop-up without blocking the page and refresh the chart every 30 seconds? <script> ...

Step-by-step guide on creating a monochrome version of an image using automation

In WordPress, I have a logo parade where all logos are in color RGB. I really like the effect of having them appear as black and white initially and then transitioning to color when hovered over. I am familiar with using sprites for this effect, but it wo ...

How can I add a blank selection at the bottom of my ng-options dropdown?

At the moment, my setup looks something like this (in a simplified form): <select ng-model=model.policyHolder ng-options="person.index as person.name for person in model.insurance.persons"> <option value>Someone else </select> This co ...

Issue encountered when attempting to utilize filters with strapi V4 graphql and nextjs, functionality not working

Currently, I am using strapi V4 along with the graphql extension. Everything works fine when I use filters with variables in the graphql Playground. query getOrdersFilterList($searchstring: String!) { orders(filters: { customer: { contains: $searchstring } ...

Observable task queuing

Here's the scenario: In my application, the user can tap a button to trigger a task that takes 2 seconds to complete. I want to set up a queue to run these tasks one after another, in sequence. I am working with Ionic 3 and TypeScript. What would be ...

Exploring the intricacies of initializing a JavaScript function

I recently inherited a large JavaScript file from a previous developer, and I'm trying to decipher some of the key sections. Here is the complete code: $(function () { var homepage = (function () { // Main functionalities are defined he ...

Issue with Slick Grid not updating after Ajax request

I need to update the data on a slick grid when a checkbox is clicked, using an ajax call to retrieve new data. However, I am facing issues where the slick grid does not refresh and the checkbox loses its state upon page load. Jsp: <c:if test="${info ...

Utilizing HTML5 history instead of hash URLs to preserve the user's browsing history

Our application is a single page that dynamically loads results based on query strings. The query string format we use is as follows: ?city=Delhi&pn=1 Within the SPA, there are different sections displayed on the same page. As users navigate through ...

Is it possible to have numerous HTML files and directories in Phonegap/Cordova along with plugins?

As I transform my web app from HTML to Cordova for enhanced device functionality, including background audio and other features, I'm encountering some challenges. Due to the original structure of my application, which consists of multiple HTML files, ...

What is the best way to convert a JSON object into a string containing a negative zero in JavaScript?

Is there a way to properly convert a negative zero into a string using JSON.stringify? I've noticed that JSON.stringify often converts negative zero into a positive one, which is not the desired outcome. Any suggestions for an alternative approach? v ...