What is the reason for the $watch function in AngularJS triggering console.log to output twice?

Here's the code snippet I've been working on:

<!doctype html>
<html lang="en-US" ng-app>
    <!--Head-->
    <head>
        <meta charset="UTF-8">
        <title>Lesson 5 - ng-show & ng-hide</title>
        <meta name="viewport" content="width=device-width">
        <style type="text/css">
            * {
                box-sizing: border-box;
            }
            body {
                font: 16px/1.5 Consolas;
                color: #222;
                margin: 5em;
            }
        </style>
    </head>
    <!--Body-->
    <body>

        <div ng-controller="information">
            <!--Input-->
            <label for="name">
                Name:
                <input type="text" name="username" id="username" placeholder="Your name here please" ng-model="name"/>
            </label>
            <br>
            <label>
                Hide?
                <input type="checkbox" ng-model="checked"/>
            </label>
            <!--Div that is hidden-->
            <div ng-hide="checked">
                Hidden Message here
                <br>
                Welcome {{ name || "user" }}!
            </div>

        </div>
        <script type="text/javascript" src="angular_1.0.7.js"></script>
        <script type="text/javascript">
            var information = function ($scope) {
                $scope.$watch(function () {
                    console.log($scope.name);
                });
            };
        </script>
    </body>
</html>

If you run this code and update the value inside the <input> tag, you may notice a strange behavior where the changed value is output twice in the console window every time you make a change. Here's why it happens:

The duplicated output in the console occurs due to the way the watch function is set up in the script. The $watch function listens for changes made to the scope variable bound to the input field 'name'. As a result, whenever the name value is updated, the $watch function triggers twice, causing the console log to display the updated value twice.

Answer №1

During each iteration of a digest cycle, watches are invoked multiple times:

The $digest loop continuously runs until the model stabilizes, meaning the $evalAsync queue is empty and there are no changes detected in the $watch list.

Whenever you type a character, Angular triggers the digest loop (as it automatically attaches an event listener due to ng-model usage) and identifies a change. It then repeats the loop once more to ensure there are no additional alterations. This step is necessary because if a $watch function causes a change in another watched property, that alteration needs to be identified for its own watch function to execute.

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

Using Rails to Pass Front-End JavaScript Data from an External API to the Controller

I need to retrieve coordinates from an external API, specifically the Google Maps API, and then send it to my controller. However, I am encountering a 500 internal server error when using jQuery/Ajax for this task. Researching the issue online suggests tha ...

JavaScript array loading failed for the C# web service

I am encountering an issue with a JavaScript object in my application that contains an array object, which is a collection of objects with two properties (Name, Value) on the server-side. Despite my efforts, when the code reaches the C# web service, the C ...

Determining if a map array value is being duplicated with a distinct key in JavaScript

I am facing an issue with a Map that has "String" as keys and "Array" as values. My problem is figuring out how to check if an array item is present in a different "Array" value, specifically in the "Array" of a different key within the map. For example: ...

What steps can I take to ensure my CSS selector for the element is functioning properly?

Here is an example of some code: <html> <head> <style> .test{ background-color: red; p { background-color: yellow; } } </style> </head> <body> <div class="test"> ...

Difficulty parsing data from a JSON file using JavaScript

My knowledge about AJAX and JSON is very limited. I am currently attempting to import the information from dealerData.json into my MVVM viewModel, however, 'data' keeps returning as undefined. $(function () { var object; $.ajax({ ...

Tips for distinguishing individual submit buttons within a foreach loop

Here is my code snippet: <?php require_once 'core/init.php'; if($result = $db->query ("SELECT * from countries")) { if($count = $result->num_rows) { $rows = $result->fetch_all(MYSQLI_ASSOC); } ...

Searching for different forms of multiple words using regular expressions

I have a value saved in a variable: var myvalue = "hello bye"; var myText = "hellobye is here and hello-bye here and hello.bye" Is there a way to check if different versions of myvalue are present in the text? I am currently using this pattern: hello ...

Exploring the world of Leaflet. Have you ever encountered situations where adding a variable name to the GeoJSON file is crucial

Currently, I am in the process of learning Leaflet, JavaScript, and more. To test my understanding, I am using code examples from the Leaflet website and making modifications for my own purposes. However, I have noticed that in all the examples I have co ...

Shut down the active tab

For some reason, using window.close(); in my JavaScript script is not closing the currently opened tab as expected. I'm looking for a way to automatically close a manually opened tab using a JavaScript function. Any ideas on what might be going wrong? ...

Adding design to distinct element after clicking a button

Struggling with a JS/Jquery issue on my portfolio website, I admit that I am still just an average programmer. My portfolio website has five buttons, each representing a different project. For each project, there is a corresponding text description and an ...

Is Typescript capable of converting ES6 code to ES5 during transpilation?

Currently, I'm in the process of developing an application utilizing Angular 2 and TypeScript. My goal is to incorporate a JavaScript method, specifically 'filter' for arrays, that is compatible with IE 11+, Chrome 45+, and other similar bro ...

Accessed a property that is not defined on the instance during rendering

One of the components I'm working on displays data that is defined in the component's state. To access this data, I created a getter: export default createStore({ state: { foo: true, }, getters: { getFoo: state => state.fo ...

Prevent duplicate items in an array by utilizing the Map object to add elements

Looking for a way to update an array by adding new values while avoiding duplicates. I've implemented the usage of a Map object to keep track of existing values and tried filtering the new array accordingly. const [items, setItems] = useState([]); ...

Obtaining a state hook value within an imported function in React

In order to access a value from the state hook stored in a special function, it is straightforward to do so in a functional component. For example, this can be achieved in App.js like this: import React from 'react'; import { Switch, Route, with ...

How can I dynamically update the sidebar in Ionic 3 post-login without the need to reload the app or refresh the browser?

I have successfully implemented login and sign up functionality in my ionic 3 app. However, I am facing an issue where the username is not updating in the sidebar instantly after logging in. Currently, I need to refresh the browser or close and reopen the ...

How to implement JavaScript alterations for ng-routed files in AngularJS without using a controller

Looking for assistance with applying JavaScript changes to ng-routed pages in AngularJS without using a controller. <nav class="navbar navbar-default navbar-fixed-top" role="navigation"> <div class="container"> <div class="navba ...

Tips on editing a file exclusively when a specific requirement is fulfilled

Looking for a way to implement a put method within an Express API that allows users to update a document conditionally? Consider this scenario: you have an Instance document with an attribute called executed, which is set to true if the instance has been e ...

A function designed specifically for parsing and manipulating hyperlinks within dynamically added content using jQuery

I have a unique one-page layout All my content "pages" are stored in separate divs, which are initially hidden using jQuery When a menu item is clicked, the inner content of the page holder is dynamically switched using html() However, I am facing an is ...

Displaying images in a horizontal row instead of a vertical column when using ng-repeat

I am currently using ng-repeat to showcase a series of images. While I believe this may be related to a CSS matter, I am uncertain. <div ng-repeat="hex in hexRow track by hex.id"> <img ng-src="{{hex.img}}"/> </div> https://i.sstatic ...

Saving base64 encoded pdf on Safari

I am facing an issue with a POST call that returns a base64 PDF. The problem arises when trying to convert it to a Blob and download it using Safari browser. This method works perfectly in all other browsers. openPdf = () => { const sendObj = { ...