我是AngularJS的新手,我有一個小問題。我有一個我想要計算平均溫度的城市列表,出於某種原因,編輯城市列表中的溫度值後,計算平均溫度的函數返回不正確的值。它加載頁面後返回正確的值,但編輯溫度值後,我得到不正確的結果。平均功能在編輯值後沒有返回正確的輸出
這裏是我的代碼:
<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>
有誰知道我在做什麼錯在這裏?
這將是,如果你設置有幫助up plunkr –