Having difficulty grasping the source of an error, as the html side is able to read list[3].main.temp
without any issues. However, in the second loop of the generateList function, I encounter an error specifically on $scope.list[i].main.temp
, which throws:
TypeError: Cannot read property '0' of undefined =\
This code is designed to select a random sample of 10 cities out of a list of 30 and display their current temperatures.
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();
};