The $watch function is triggered even when the expression remains unchanged

Within my controller, I have a variable named datetime that gets updated by a timer every second. What I need to accomplish is some work when the day changes. To achieve this, I set up the following watcher:

$scope.$watch("datetime | date: 'MM/dd/yyyy'", function (newDate, oldDate) {
    console.log(newDate === oldDate);
}, true);

However, I'm noticing that this listener is initially triggered with newDate equaling oldDate. Can anyone shed light on why this might be happening? The code responsible for updating datetime looks like this:

var timeoutId;

function startTimer() {
    timeoutId = $timeout(tick, 1000);
    timeoutId.then(startTimer);
}

function stopTimer() {
    $timeout.cancel(timeoutId);
    timeoutId = undefined;
}

function tick() {
    $scope.datetime = new Date();
}

$scope.init = function () {
    startTimer();
}

The $scope.init() function is invoked via ng-init.

Answer №1

As stated in the provided documentation:

The listener will only be activated when there is a variance between the present value from the current watchExpression and the previous evaluation of watchExpression (excluding the initial execution, as stated later).
[...]
Once a watcher has been implemented within the scope, the listener function will trigger asynchronously (via $evalAsync) to inaugurate the watcher. It may occasionally lead to undesired outcomes since the listener can be invoked even if the result of watchExpression remains unchanged. To identify this situation while inside the listener function, one can compare the newVal with oldVal. When both values are identical (===), it signifies that the listener was summoned during the initialization process.

To address this issue, you should adjust your $watch like so:

$scope.$watch("datetime | date: 'MM/dd/yyyy'", function (newDate, oldDate) {
    if (newData !== oldDate) {
        /* Value has changed: Carry out necessary actions */
        console.log(newDate === oldDate);
    }
}, true);

Answer №2

Make sure to prevent the $watch function from being triggered during the initial load by using a flag.

var loaded = true;
$scope.$watch("timestamp | date: 'MM/dd/yyyy'", function (newTime, oldTime) {
    if(!loaded){
       console.log(newTime === oldTime);
    } else {
        loaded = false;
    }
}, 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

AngularJS offers a full calendar feature that includes various views such as year, month, and week

I want to showcase a Full Calendar on my web page using AngularJS. I am looking for detailed steps to achieve this. Set up the UI calendar with full functionality Add events to populate the calendar Implement actions for the events Since I am new to Ang ...

Issue with utilizing addEventListener("load") in Firefox in conjunction with <iframe>

I've encountered an issue with my iframe when it is used as the target for a form. In all major browsers, except for Firefox, the iframe successfully removes the main element upon pressing the submit button. However, in Firefox, the main element is re ...

The PDF file cannot be displayed due to the dynamic loading of the path and filename

Currently, I am working on an AngularJS and Java application. The following HTML code is utilized to open a PDF file in the browser. However, there seems to be an issue where the PDF does not open when dynamically passing the value for the data attribute. ...

Break down objects into arrays of objects in JavaScript

Hello, I'm struggling with transforming this object into an array of objects. The 'number' and 'reason' fields are currently stored as strings separated by commas. I need to split them into their own separate objects. The example ...

Testing Angular 1.5 Directive with ng-include Template

Having trouble testing the UI state of a directive that loads templates dynamically via ng-include. Initially, there were issues with the element being undefined, but after some research, I found that wrapping the compiled element with a parent HTML elemen ...

Angular Bootstrap notifications will stay open indefinitely and will not automatically dismiss after a certain period

I need help with adding alerts using Angular Bootstrap that should dismiss themselves after a certain timeout. However, the alerts are not dismissing on their own. Here's the code snippet: angular.module('ui.services').service('AlertSe ...

Methods for incorporating rtl functionality into Angular Chosen

I am currently using Angular with Chosen (source) and I am attempting to implement right-to-left (RTL) support. Here is my demo, but despite referencing resources, I am encountering issues. The main problem arises when the body element has a dir="rtl" att ...

Ways to determine if a web browser is executing javascript code (without altering the javascript on the webpage)

Working on creating a custom PHP client for Selenium, I've encountered an issue with implementing the waitForPageToLoad() function: The problem lies in just checking the document.readyState, as there could be JavaScript scripts running on the page (l ...

Display a Loading Indicator within a Bootstrap 4 Modal Dialog

I have a question regarding Bootstrap 4 and a simple trick I am trying to implement. I am looking to display a Loading indicator similar to Twitter every time the user opens the modal. I have some code that is working well, but I seem to have misplaced som ...

Combining React Material UI with an endless scrolling component to dynamically load table data

I need some help with using react infinite scroll within a react material table. I attempted to implement it but the scrolling affected the entire page instead of just the table body. I want the headers to remain sticky while only the table body should h ...

Adjust the height of a div in JQuery to fit new content after specifying a height previously

I have a division element with an initial height of 0 and opacity set to zero, its overflow is hidden, and it contains some content. <div style='height: 0px; opacity: 0px; display: none; overflow: hidden; border: 1px solid #000;' id='myd ...

Having trouble with filtering the Date field in ngTable within an angularjs project

Currently tackling an issue with the date field filter in an angularjs ngTable project. Specifically, when typing '2018' into the filter, no results are being displayed on the table. I attempted to filter the date field as text using filter="{ or ...

How can I retrieve the body from a GET request using Express?

Every time I attempt to execute my code, it returns an error message indicating invalid text. app.post("/charge", (req, res) => { console.log(req.body) }) ...

Begin by directing your view towards an object with FirstPersonControls

When I have FirstPersonControls enabled, my camera.lookAt(cube.position) doesn't work. How can I make it so that I start exploring by automatically looking at the object first? Thank you, ...

Cannot assign value to property x on y as it is not an object - dealing with Multidimensional Arrays

I'm experimenting with creating a multidimensional array that looks like this: var minutes = []; for (let i = 1; i < 10; i++) { minutes.push(i); } var works = [{ startTime: 80000, endTime: 150000 }, { startTime: 200000, endTime: 400000 ...

Unfortunately, the Ajax functionality is not performing as expected

What am I missing? 2.php: <button id = "Text_Example">Display</button> <script src="jquery-3.1.1.min.js"></script> <script src="js_code.js"></script> js_code.js: $("#testtext").bind("click", displayNewData); functio ...

PhoneGap and Ionic - Issue with $scope not updating within a click function

I'm facing a peculiar issue in my simple setup - I want to click a button and retrieve the data from an input control. The problem lies in the fact that the $scope variable inside the click function retains its initial value, instead of updating as ex ...

What is the best way to manipulate a shape in Snap.svg while ensuring the transformation does not affect its mask?

My current challenge involves transforming a rectangle with position, scale, and angle adjustments while having it masked. To illustrate my issue, I have created a fiddle file which can be accessed via this link: http://jsfiddle.net/MichaelSel/vgw3qxpg/2/ ...

Use various onChange functions for sliding toggle

I need assistance with a toggle app I'm developing that includes two slide toggles. Even though I have separate onChange() methods for each toggle, toggling one slide-toggle also changes the value of the other slide toggle. The toggle state is saved i ...

Leveraging Javascript to identify actual text content, rather than focusing on HTML elements

Having an issue with a WYSIWYG editor (TinyMCE) saving content into the database where values are sometimes saved that contain only tags like: <p><br data-mce-bogus="1"></p> which is not actual content. My application cannot distinguis ...