TypeError:无法在angular app中读取未定义的属性“0”

时间:2015-06-20 13:33:25

标签: javascript asp.net angularjs

我无法理解错误的来源,因为html方面很好地选择list[3].main.temp之类的东西,但是在generateList函数的第二个for循环中,我在$scope.list[i].main.temp上得到错误说

  

TypeError:无法读取undefined = \

的属性“0”

该代码应该包含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();
};

2 个答案:

答案 0 :(得分:0)

问题可能是在运行回调之前$scope.list未定义。你可以从$scope.getWeather返回一个promise并在$scope.generateList中解析它,然后在检索数据时(在回调中)执行for循环,例如。

$scope.getWeather返回承诺:

$scope.getWeather = function () {
  ...
  return $http.jsonp(...)
}

然后在$scope.generateList

...
$scope.getWeather().success(function(data, status, headers, config) {
  $scope.data = data;
  $scope.list = data.list;
  for (var i = 0; i < $scope.displayNum; ++i) {
    $scope.display.temp.push($scope.list[i].main.temp);
  };
}

或沿着这些方向的东西。

答案 1 :(得分:0)

$ scope.display是一个List使用另一个变量

{{1}}

enter image description here