Why is the count's answer 88?

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">        </script>
</head>
<body>
    <div ng-app="myApp" ng-controller="personCtrl">{{count()}}</div>
    <script>

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

    app.controller('peopleController', function($scope) {
        $scope.items=[1,2,3,4];
        var count=0    

        $scope.countItems = function() {
            angular.forEach($scope.items,function(value,key){
                count=count+1;
            });
            return count;
        }
     });
   </script>
</body>
</html>

The output displayed by the above code is 88. The value of var count changes based on its placement within or outside the count function. When inside the function, it shows 4, but when declared outside, it shows 88. Why does this occur?

Answer №1

The explanation for this behavior is due to the fact that you connected the count() function to $scope and utilized it within a binding expression. In AngularJS, the $digest cycle, which assesses expressions and renders the view, can iterate multiple times.

If we were to represent the $digest cycle in pseudocode, it would appear as follows:

  1. Iterate through each property of $scope
  2. Determine if there have been changes in $scope properties (e.g., by evaluating binding expressions)
  3. If changes are detected, trigger change handler (which could potentially update more scope variables), otherwise continue
  4. Repeat process for all scopes
  5. Continue cycles 1-4 until $scope properties stabilize

Answer №2

Instead of using a function or each loop, you can simply utilize the length property like this: $scope.listarray.length; Give it a try:

<head>
<script src=        "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">        </script>
    </head>

  <body>

 <div ng-app="myApp" ng-controller="personCtrl">
 {{count}}

  </div>

 <script>

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

  app.controller('personCtrl', function($scope) {
   $scope.listarray=[1,2,3,4];

   $scope.count =  $scope.listarray.length;    
     });
   </script>

    </body>
   </html>

Answer №3

You seem to have accidentally created an infinite loop in your code. This is likely happening because your function count() is being called every time the value changes. To prevent this, you could add a check to see if the value has already been changed before running the function.

 $scope.count = function() {
        if(count !== 0){return count;}
        angular.forEach($scope.listarray,function(value,key){
            console.log('value', value);
            count=count+1;
        });
        return count;
    }

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

Applying these sorting functions to my specific scenario

Hello everyone, I hope you can help me out with this issue. I have been struggling for hours trying to sort my array of objects in JavaScript based on a specific property, but I just can't seem to get it right. I have referred to some of the top post ...

The list in Jquery UI Autocomplete is not updating correctly

Currently, I am using jQuery UI Autocomplete in conjunction with WebSockets to fetch and display a list of options. Each time a keystroke is detected on the input field (.keyup()), a call is made to retrieve the list. However, I have encountered an issue w ...

Setting a value to a FormBuilder object in Angular 2 with Typescript

During my use of Reactive form Validation (Model driven validation), I encountered an issue with setting the value to the form object on a Dropdown change. Here is my Formgroup: studentModel: StudentModel; AMform: FormGroup; Name = new FormControl("", Va ...

Similar guidelines not following suit

Within the same module are both of these directives. Primary directive: .directive('welcomeAndLog', function() { return { restrict: 'A', template: "<div ng-show=\"currentUser.get('username&a ...

a function that is not returning a boolean value, but rather returning

There seems to be a simple thing I'm missing here, but for the life of me, I can't figure out why the function below is returning undefined. var isOrphanEan = function isOrphanEan (ean) { Products.findOne({ 'ean': ean }, func ...

Implementing dynamic webpage updates based on dropdown list selections

In my webpage, I am displaying a list of movies fetched from an API. The issue I am facing is related to sorting the movies based on user selection. When I uncomment one of the sort methods in my code, it works as intended. What I want to achieve is that ...

I'm currently attempting to establish a connection between my server.js express API and MongoDB, but I keep encountering an unfamiliar error message that I'm having trouble decipher

Here is the server.js code: import express from 'express'; import bodyParser from 'body-parser'; import userRoutes from './routes/users.js'; import mongoose from 'mongoose'; co ...

Displaying a horizontal scroll bar for legends in ECharts can be achieved by limiting the legend to three lines. If the legend items exceed this limit, they will scroll horizontally to accommodate all items

I am currently utilizing ECharts to display trend data in a line chart format. With 50 different series to showcase, each series comes with its own legend. My objective is to arrange the legends at the top of the chart, while limiting them to a maximum of ...

Tips on updating pinned row information in AG Grid Vue

I have a specific row pinned to the bottom in the grid. Whenever I add or remove some rowData in the grid, I need to update that pinned row. Take a look at the code snippet below: this.gridApi.pinnedBottomRowData = rowNode.setDataValue(date, dataToPush); t ...

Tips for removing cookies with Javascript after an allotted period of time

I need to remove a specific cookie value that I set after a certain time period. For example, I want the cookie to be deleted after 10 seconds. function fullday() { document.getElementById("res").innerHTML="1 day"; document.cookie="day="+1; do ...

Tips for identifying, initiating, and linking to the mobile version of Metamask through a button click on a web application, similar to the process on OpenSea

I recently integrated a shortcode into my project that leverages the Metamask browser extension to display the user's account using a combination of web3 and reactjs. The code functions flawlessly on desktop browsers, but encounters an issue when atte ...

Angular's asynchronous HTTP request allows for non-blocking operations when

I'm currently working with Angular 6, and I've encountered an issue while updating my resource instance in the following way: this.user = api.getUser(); public getUser(): User { const myHeader = new HttpHeaders({ 'Authorization' ...

The ConsoleCapture does not capture every console error for Sentry

Running into an issue capturing console errors with Sentry in a Next.js app. The problem arises from an error within a library that is inaccessible to us, specifically related to WebSocket "WebSocket is already in CLOSING or CLOSED state" This error is c ...

The ajax signal indicates success, yet there seems to be no update in the database

Hey there, thank you for taking the time to read this. Below is the code I'm currently working with: scripts/complete_backorder.php <?php if(!isset($_GET['order_id'])) { exit(); } else { $db = new PDO("CONNECTION INFO"); ...

Tips for revealing a hidden div by clicking on another div?

I have a Google visualization chart inside a div tag. I would like to display this chart in a pop-up box when clicking on the chart's div. I am utilizing jQuery for this feature. ...

Dragula model failing to update source array

I've been experimenting with angular-dragula for a small test code and I've successfully implemented the drag-and-drop feature, but I'm facing an issue with updating the source data array. In the angular controller, I define some variables: ...

Pause before sending each request

How can we optimize the Async Validator so that it only sends a request to JSON once, instead of every time a letter is typed in the Email form? isEmailExist(): AsyncValidatorFn { return (control: AbstractControl): Observable<any> => { ...

Removing Discord Channel with Discord.js

Currently in the process of developing a ticket system using discord.js Experiencing a challenge where upon a member reacting to the message with a specific emoji, the ticket is supposed to close. However, when running the code, it is throwing an error. i ...

Mocking `window.location.reload` in unit tests - "Looks like your tests triggered a full page refresh!"

In one of my controllers, I have the following code snippet: $scope.foo = function(){ return RolesService.remove({ data: role }) .then(function (v) { if (!(v && v.cdtError)) { $window.location.reload( ...

The JavaScript code is producing a numerical output instead of the intended array

I am facing an issue with my program that is designed to eliminate items from a list of arguments. function destroyer(arr) { var args = [].slice.call(arr); var data = args.shift(); for(var i = 0; i < args.length; i++){ var j = 0; while(j ...