Angular watch triggering even when the old and new values remain unchanged

        function displayController($scope) 
{

    $scope.currentView = myCustomInstance.currentView;


    $scope.$watch($scope.currentView, 
            function(newValue, oldValue)
            {       
                console.log(newValue);
                console.log(oldValue);

                console.log($scope.currentView);

                if($scope.currentView != null)
                    $scope.data = $scope.currentView.dataset;  
            }
        );

}   

Output in console:

undefined script.js:10
undefined script.js:11
null 

The object myCustomInstance represents an instance of a custom JavaScript class I developed. Initially, its currentView is set to null but changes value once the instance is created.

Answer №1

I'm not sure why the $watch function doesn't automatically handle this issue, but you are correct in your assessment. The $watch callback will trigger whenever there is a change in or an update to the reference of your $scope attribute. This means that the callback will be triggered even if the reference is updated to the same previous value.

To resolve this issue, follow these steps:

$scope.$watch('current_view_', function(newVal, oldVal){
    if(newVal != oldVal){  // do nothing if values are the same
        // include the rest of your code here, such as:
        $scope.dataset = $scope.current_view_.dataset;
    };
});

The watcher callback will still be activated, but it will now take no action when unnecessary. The $watch callback will continue to be triggered each time the reference to $scope.current_view_ changes, but it will only modify the $scope.dataset value if it changes to a different value than before. Does this explanation make sense?

Answer №2

During the $watch event, there is typically a difference between oldValue and newValue, except for one specific case: when the watcher is initialized. This means that on the initial run of the function, oldValue may equal to newValue. AngularJS documentation explains this as:

Once a watcher is added to the scope, the listener function is asynchronously called (via $evalAsync) to set up the watcher. In some rare instances, this may not be desirable because the listener gets triggered even when watchExpression remains unchanged. To identify this situation within the listener function, you can compare newVal and oldVal. If they are exactly the same (===), then the listener was activated due to initialization.

Answer №3

When using $watch, the callback is only triggered when the value changes, unless it is during initialization. This explains why the output displayed is related to initialization. In future instances, the callback will be activated with a new value that is not undefined.

It seems like you didn't pose a question or mention any specific issue you are facing. Perhaps you were taken aback by the fact that the old and new values can be the same in a $watch callback.

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 is the best way to change a variable in an AngularJS view?

My Request In my application, I have implemented 3 views, each with its own controller. The first view is the home screen, and from there the user can navigate to view 2 by clicking on a div element. On view 2, the user can then move to view 3 by clicking ...

ng-repeat and $scope problem

I am having an issue with my page where I display 3 images in a row using Ng-repeat. When I click on any image, it only shows the first image that was displayed in that particular row. Template: <div id="galscrolldiv" class="row" ng-repeat="image in i ...

Exploring the basics of Three.js: a step-by-step guide using a shadertoy example on transforming patterns with objects

Check out this snippet, inspired by the second live example found at : html, body { height: 100%; margin: 0; } #c { width: 100%; height: 100%; display: block; } <canvas id="c"></canvas> <script type="module"> // Three.j ...

Retrieve a result from this promise

I have encountered a problem that my classmates at school cannot solve. I have a piece of code that is working fine and sending the table of objects potentials to the client side. However, I now realize that I also need another object called userData. I ...

Running Javascript code to perform drag and drop in Selenium for UI integration testing in Java

I am currently working on a task involving writing UI test cases (Automation) using Selenium in Java. I have an HTML page with an element that needs to be dragged to a target. Despite trying the Action functionality in Selenium, it didn't work for me. ...

Unable to get i18next functioning in my Node.js Express backend

I'm currently facing difficulties in implementing localization for my nodeJS backend. Within my Angular frontend, I have a language-setting interceptor that successfully sets the language in the request header. You can refer to the image below which ...

The ng-view component in Angular seems to be causing issues with the routing functionality

I'm having trouble getting this to function properly. I've included the relevant code snippet, let me know if you need more details. Index.html <div class="col-md-3"><a href="#/liberals">Liberals</a></div> app.js var ...

Learn the method for invoking a service from a different module using $on and $broadcast

I am attempting to establish communication between factory A and factory B in Angular by using the $broadcast method. These two factories are located in different modules. Below is the code snippet that demonstrates my approach. angular.module('secon ...

nodemon encountered an error and is currently on standby for any updates before restarting

UPDATE Upon further investigation, I have discovered that both gulp and grunt are experiencing issues in this application as well as the default installation of mean.js. This is while running the app locally on a Mac. Interestingly, when I start either app ...

interaction & portal

I am currently managing a website that includes an iframe. Both the main site and the embedded site within the iframe are verifying the $_SESSION["login"]. Therefore, if the session expires, the user will be automatically logged out. The issue I'm fa ...

Performing additions on two-dimensional arrays using Angular/JavaScript

Currently, I am in the process of learning basic JavaScript and could use some assistance. My task involves working with two-dimensional arrays where the 0th index will always represent a date and the 1st index will always be an integer in the array. My go ...

AngularJS written plugin in Javascript

I developed an app using Rails and AngularJS. A startup has reached out to me about transferring the technology to their website, but they have limited tech resources. The goal is to create a seamless integration process. The idea is to make it similar to ...

Is there a way to modify the space bar and enter key functionality exclusively for the third button, rather than applying it to all buttons?

https://jsfiddle.net/ffkwgddL/ In the code, I have three buttons named first-button, second-button, and third-button. If the first-button (introduction) is clicked and then the space bar is pressed, it functions as if the first button was clicked again. H ...

Guide to automatically update div with new table rows with the help of Ajax

Can you assist me in updating the div called "table" that contains a table fetching rows from the database? <div id="table"> <h1 id="Requests"> <table></table> </h1> </div> <button id="refresh-btn"&g ...

Merging Data from Multiple Forms in an Angular Application

I am currently working on my first Angular project and although I have made significant progress, I have reached a point where I feel I need assistance to complete it successfully. Project Overview: I have a class mod.ts export interface Mod { id : ...

Tips for preventing the extraction of resolve from promises and initiating a process before a callback

There is a common pattern I frequently find myself using: const foo = () => { const _resolve; const promise = new Promise(resolve => _resolve = resolve); myAsyncCall(_resolve); return (dataWeDontHaveYet) => promise.then(cb => c ...

Retrieve the specific key or object number by conducting a search in JavaScript

I am faced with the challenge of editing a large XML file by searching for a specific keyword within the "event name" field and changing the corresponding "active" value to either 1 or 0. The structure of the data file is as follows. I have managed to modi ...

Unable to apply CSS styles to a form input using Ajax

Alright, so I've got this Ajax form that successfully fetches the data and displays it in #register_msg. However, I'm also trying to apply some styles to the input forms. Here's my Ajax code, along with the form. But for some reason, the st ...

What is a method to mimic the presence of JavaScript using PHP Curl?

Is it possible to parse HTML code from a webpage using PHP Curl even if there is an error message stating that JavaScript is required to access the site? Can PHP Curl be used to enable JavaScript on a webpage? ...

Ways to verify if the CSS background-color is set to white?

I am looking for a solution: $('*').click(function() { if($(this).css("background-color") == "#ffffff") { $(this).css("background-color") == "#000000" } });​​​​ that will execute on click of a specific cla ...