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?