Unexplained quirks observed in AngularJS $watch during the initialization of a controller

I am working with a code snippet that utilizes AngularJS:

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

app.controller('DemoCtrl', function ($scope) {
  function notify(newValue, oldValue) {
    console.log('%s => %s', oldValue, newValue);
  }

  $scope.$watch('collection.length', notify);
  $scope.$watch('my', notify);

  $scope.collection = [];  
  $scope.my = 'hello';
});

The $watch function fires initially. When running this code snippet, the following output is generated:

0 => 0
hello => hello 

Is this behavior correct? While I could check values for equality, what are the reasons behind this particular behavior?

P.S. You can try out this sample online: http://jsbin.com/otakaw/7/edit

Answer №1

As stated in the provided documentation:

The listener will only be triggered when there is a difference between the current value of the watchExpression and its previous value (excluding the initial execution, which is a special case as explained below).

Once a watcher is set up within the scope, the listener function is invoked asynchronously (through $evalAsync) for initialization purposes. In some uncommon situations, this may not be desirable as the listener gets called even if the result of the watchExpression remains the same. To handle this situation within the listener function, you can compare the newVal with the oldVal. If these values are exactly the same (===), it indicates that the listener was executed during the setup phase.

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

Access a file from a specified route within Express

Recently, I created a custom Node module that requires a configuration file in CSV format. My goal is to implement this module within an Express Route module; however, I am encountering difficulties related to the loading of the configuration file. Should ...

Sending information to a component through navigationPassing data to a component

When attempting to move from one component to another page using routes and needing to send parameters along with it, I have experimented with passing them as state through history.push(..) like the following code. However, it does not seem to be working a ...

Ways to transfer large amounts of data to Amazon Web Services

After reading the node documentation on sqs.sendMessage, I noticed that it mentions the ability to send messages up to 256KB in size. However, my messages tend to exceed this limit. What is the recommended approach for handling large payloads in this scena ...

One way to organize data from my API is by sorting it based on two date conditions. If one of those conditions is missing, the data should be placed at the beginning of the list

I am facing a challenge with sorting the return from my API based on the StartDate. However, I need to implement a validation where if there is no FinalDate provided, the data should appear at the first index of the result. StartDate: "2004-06-04" ...

The issue of controller inheritance not functioning properly when using the controller as syntax has

Here is the basic structure of the HTML: <data> <definition-data></definition-data> </data> In my data template file, I have the following code that works as expected: <div ng-controller="dataCtrl as dataitems" ng-cloak> ...

Combining various data types within a single field in BigQuery

Is it feasible to specify a table schema with a field that allows for multiple data types? For instance: BIGQUERY TABLE SCHEMA schema: [{ name: 'field1', type: 'string', }, { name: 'field2', type: &apo ...

Bringing in PeerJs to the NextJs framework

Currently delving into NextJs and working on creating an audio chat application, I've hit a roadblock while attempting to import PeerJs. An error message keeps popping up saying 'window is not defined'. import Peer from 'peerjs'; ...

How to effectively test a form submission with an external API using React, Jest, and Enzyme?

I have integrated a geocoding API to verify address submissions on a form. Upon submitting the form, the geocoding API is called first, followed by validation of the remaining form fields. class Form extends React.Component { geocode = (streetAddress, cit ...

What is the best way to incorporate a background image in a Bootstrap tooltip?

I'm having trouble displaying an element with a background-image property within a Bootstrap tooltip. The image is not showing up as expected. <div class="big-panel"> <a href="#" data-bs-toggle="tooltip" data ...

Refining/searching with selectors in AJAX response

As someone who is new to javascript and coding in general, I am facing a challenge with filtering and manipulating data received through an AJAX request. Unfortunately, I do not have access to the server-side code. The server responds with rota information ...

Which is better: specifying Node.js version with nvmrc or in package.json engines

Ensuring that other developers working on my JavaScript project use specific versions of node and npm is important to me. I recently added the following code snippet to my package.json file: "engineStrict" : true, "engines": { "node" : "10.10.0", ...

How to retrieve the value of an element within a facebox div with jquery

On my page, I have two div tags displayed below. Whenever I try to retrieve the value of the itemName element using $('#itemName').val();, it always returns the value of the element in the first div (which is blank). Is there a way to access the ...

Click the submit button to display a div element without having to refresh the page

Is it possible to display a spinner for a couple of seconds before the page reloads upon submitting a form? <form class="ready" action="https://link.com" method="post"> <input name="test" type="submit" class="click" value="order"/> </form&g ...

Should one consider using the Express app.use() method within an asynchronous callback function?

Seeking advice on a recommended best practice. I recently developed an Express server that generates a JWT and sends it to the client whenever they hit an API endpoint. To maintain modularity, I separated the route handler into its own module and exporte ...

I am experiencing difficulty with the function from flip.to not functioning properly on my Next.js project

I was given this script by flip.to <script> !function(b,e){ (b[e] = b[e] || []).push({ flipto: { bookingEngine: "Demo", companyCode: "XX", code: "YYYY", ...

Utilizing ReactJS to creatively overlay a video on top of an image with the option to

Is there a method to superimpose a video onto an image while having the ability to select the blending mode for them? Similar to how Photoshop and Final Cut provide various blending modes such as Overlay, Multiply, Add, etc. Could there possibly be a libr ...

Revolutionary Knockout-Kendo MultiSelect Feature: Pressing Enter Erases Previously Selected Options

When using the Knockout-Kendo MultiSelect control, I have encountered an issue. If I select a value from the list, then enter a second value and press enter, the previously entered values are removed. VIEW <select data-bind="kendoMultiSelect: { da ...

Lighthouse Issue: Facing PWA Challenges with a "Request Blocked by DevTools" Error

For hours now, I've been struggling to make Lighthouse work in Chrome for my initial PWA project. I feel completely lost as nothing seems to be making sense despite the basic code I have included below. The issue arises when I load the page normally ...

AWS Lambda applies quotes to create the event input

I'm encountering a problem with my Python 3.8 AWS Lambda function that is meant to handle form inputs from a web application. The data from the form inputs gets passed to the Lambda function and ends up in the event dictionary. However, lambda seems t ...

The navigation links in my React project are not appearing on the screen as expected

Hello everyone, I am relatively new to React and recently I have been attempting to utilize `react-router` in order to construct a Single Page Application. My goal is to link all the pages (such as Home, About, Login, etc) in the navigation bar using the & ...