我無法理解錯誤的來源,因爲html端拿起像list[3].main.temp
就好,但在第二個for generateList函數循環中我得到在$scope.list[i].main.temp
它說TypeError:無法讀取角度應用程序中未定義的屬性'0'
TypeError: Cannot read property '0' of undefined =\
錯誤右邊的代碼應該採取30個城市的名單,隨機挑選10和顯示其當前溫度。
var WeatherApp = angular.module("WeatherApp", ["ngRoute", "ngResource"]).
config(function ($routeProvider) {
$routeProvider.
when('/', { controller: ListCtrl, templateUrl: 'list.html' }).
otherwise({ redirectTo: '/' });
});
WeatherApp.factory('City', function ($resource) {
return $resource('/api/City/:id', { id: '@id' }, {update: { method: 'PUT'}});
});
var ListCtrl = function ($scope, $location, City, $http) {
$scope.city = City.query();
$scope.units = 'metric';
$scope.appId = '';
$scope.displayNum = 10;
$scope.display = [];
$scope.display.temp = [];
$scope.generateList = function() {
$scope.exp = City.query(function (exp) {
shuffle(exp);
$scope.cityIdAr = [];
for (var i = 0; i < $scope.displayNum; ++i) {
$scope.display.push($scope.exp[i]);
$scope.cityIdAr.push($scope.exp[i].CityId);
};
$scope.cityId = $scope.cityIdAr.join();
$scope.getWeather();
for (var i = 0; i < $scope.displayNum; ++i) {
$scope.display.temp.push($scope.list[i].main.temp);
};
});
};
function shuffle(ob) {
for (var j, x, i = ob.length; i; j = Math.floor(Math.random() * i), x = ob[--i], ob[i] = ob[j], ob[j] = x);
return ob;
};
$scope.getWeather = function() {
var url = 'http://api.openweathermap.org/data/2.5/group';
$http.jsonp(url, {
params: {
id: $scope.cityId,
APPID: $scope.appId,
units: $scope.units,
callback : 'JSON_CALLBACK'
}
}).success(function (data, status, headers, config) {
$scope.data = data;
$scope.list = data.list;
});
};
$scope.generateList();
};
【如何返回從異步調用的響應?](http://stackoverflow.com/questions/14220321/如何返回來自異步調用的響應) – Andreas