I am new to AngularJS, and I have a slight problem. I have a list of cities that I would like to compute the average temperature, and for some reason, after editing the temperature values in the list of cities, the function to compute the average temperature is returning incorrect values. It returns the correct value after loading the page, but after editing the temperature values I get incorrect results.
Here is my code:
<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 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}
];
//returns incorrect average values after editing default temperature values
$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>
Does anyone know what am I doing wrong here?