The average calculation malfunctioning after adjusting the input data

I am a beginner with AngularJS and facing an issue. I have a list of cities for which I need to calculate the average temperature. However, after editing the temperature values in the city list, the function that computes the average temperature is giving incorrect results. It seems to work fine initially when the page loads, but after modifying the temperature values, it starts showing inaccurate results.

Below is the code snippet:

<html ng-app>
<head>
    <title>Weather Comparison</title>
</head>
<body ng-controller='WeatherController'>
<h1>Weather Comparison</h1>
<div ng-repeat='item in items'>
    <span>{{item.city}}</span>
    <input ng-model='item.temp'>
    <input ng-model='item.humidity'>
    <input ng-model='item.wind'>
    <input ng-model='item.cloudiness'>
</div>
<div>The calculated average temperature is {{avgTemp}}</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script>
    function WeatherController($scope) {
    $scope.items = [
        {city: 'Phoenix,AZ', temp: 38, humidity: 10, wind: 3, cloudiness: 10},
        {city: 'Atlanta,GA', temp: 30, humidity: 80, wind: 7, cloudiness: 40},
        {city: 'Honolulu,HI', temp: 32, humidity: 75, wind: 8, cloudiness: 30}
    ];

    //Issue with computing average after editing default temperatures
    $scope.$watch(function() {
        var sum = 0;
        for (var i = 0; i < $scope.items.length; i++) {
            sum += $scope.items[i].temp;
        }
        $scope.avgTemp = sum / $scope.items.length;
   });
}

</script>
</body>
</html>

I'm puzzled by the inconsistency in the average temperature calculation. Any ideas on what might be causing this discrepancy?

Answer №1

To convert a string representing temperature to an integer, you can use the following code snippet (DEMO):

total += parseInt($scope.list[i].temperature, 10);

If you prefer to work with floating point numbers:

total += parseFloat($scope.list[i].temperature);

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

Having trouble getting your Bootstrap v4 carousel to function properly?

Currently, I have implemented the carousel feature from Bootstrap v4 in a Vue web application. I am following the same structure as shown in the sample example provided by Bootstrap, but unfortunately, it is not functioning correctly on my local setup and ...

`When trying to utilize $uibModal.open within karma (AngularJS Factory), an error is encountered as it

My current task involves testing a function that triggers the opening of a $uibmodal. Below is my factory function: confirmationMessage: function (message) { var modalInstance = $uibModal.open({ templateUrl: 'views/templates/utilsTemplates/ ...

Troubles encountered when populating the array within a Vue component

I am experiencing an issue with my ProductCard component where the addItem method is not successfully adding a new item to the array. <template> <div class="card"> <div v-for="item in TodoItems" :key="item.id ...

Tips for creating a secure authentication system in an AngularJS application!

As a novice in the world of angularjs... After going through the documentation and completing a tutorial, I decided to experiment on my own which has helped me grasp things better. Now, I'm looking into creating a secure authentication system. The ...

If an error occurs later in the function, `console.log` will not function properly

While debugging some code in Express.js using console.log statements, I encountered an issue where the console.log statements do not execute if there's an error in the function, even if that error occurs after the console.log statement. This behavior ...

Identifying duplicate values in an array of objects using JavaScript

I am facing an issue with my array that collects data from a spreadsheet into studentCCAList. Sometimes, a student may have multiple subjects. For example, Name: Joseph Subject: English Name: Peter Math Name: Joseph Subject: Science My concern i ...

User interaction with a checkbox triggers a state change in Angular

Here is the code snippet I am working with, where clicking should set the checked value to false: @Component({ template: ` <input type="checkbox" [checked]="checked" (change)="onChange()"> ` }) export class AppC ...

Attempting to transfer various variables from several windows using AJAX

Is it possible to pass multiple variables from two different windows into the same PHP script? If not, what would be the best approach to take? Thank you. verifyemail.html <script type = "text/javascript" src = "js/js_functions.js"></script> ...

The way an event can be outrun or vanish due to another event

let bar = new function(){ $scope.MessageSpan="Item added successfully";} When the Add button is clicked, the above function is invoked. However, if I want to hide this message when any other button is clicked, I would have to update the span text for all ...

Looking to transform a nested JSON structure into a visually appealing HTML table with merged rows?

My JSON structure appears as follows: $scope.data = [ { "type":"Internal", "count": 3, "library" : [ { "type":"Library 123", "count": 2, "version" ...

Prevent Click Event on Angular Mat-Button

One of the challenges I'm facing involves a column with buttons within a mat-table. These buttons need to be enabled or disabled based on a value, which is working as intended. However, a new issue arises when a user clicks on a disabled button, resul ...

When there is an error or no matching HTTP method, Next.js API routes will provide a default response

Currently, I am diving into the world of API Routes in Next.js where each path is structured like this: import { NextApiRequest, NextApiResponse } from "next"; export default async (req: NextApiRequest, res: NextApiResponse) => { const { qu ...

Having trouble accessing parameter values in a React app using ES6 arrow functions

Hey there! I've been attempting to send values to an ES6 arrow function in my React application, but unfortunately, it's not working. Here's what I'm trying: var data = []; for (var i=1; i<=5; i++) { data.push(<li><a href ...

What is the best way to choose all checkboxes identified by a two-dimensional array?

I need help with a question div setup that looks like this: <div class="Q"> <div id="Q1"><span>1. </span>Which of the following have the same meaning?</div> <div class="A"><input type="checkbox" id="Q1A1Correct" /& ...

Tips for posting images upon clicking a div instead of a submit button

I previously had a code that allowed users to click on the submit button and have the text inside a contenteditable div passed to upload.php using JQuery, inserted into a database, and immediately displayed. Now, I want to modify this code to also handle i ...

The onChange function in Material UI Text Field is preventing users from inputting additional values

My application contains a custom TextField component. I am facing an issue where I cannot increase the value of the first TextField due to the presence of the onChange method. However, the second TextField does not have the onChange method, and I can succe ...

Display HTML components as JSON data using AngularJS

Recently, I started exploring angular js and faced a challenge in formatting json data with the help of angular js. Below is a snippet of my json data: [ {"field_add_link": "<a href=\"/drupal3/drupal3/\">Home</a>"}, {"field ...

The for...of loop cannot be used with the .for property since it is not iterable. (Is

let arr = [{ category: 'music', views: 20 }, { category: 'abc', views: 32 }, { category: 'bob', views: 20 } ] for (const [key, value] of arr) { console.log(key, value) } console.log(Array ...

Utilizing Bootstrap to arrange table cells in a shifted manner

I'm new to utilizing bootstrap in web development. I've been exploring various examples of bootstrap templates that include tables, and I noticed that when I resize my browser window, the table adjusts accordingly. Now, I'm curious to know ...

Utilizing loop variables in ng-class and ng-click directive

This piece of code generates a list consisting of seven thumbnails, with the currently active image designated by the active and thumb classes. <div ng-repeat="no in [1, 2, 3, 4, 5, 6, 7]"> <img ng-src="images/{{no}}t.jpg" class="thumb" ng ...