抱歉我的英语不好。
chill.controller('messagesController', function($scope, $http, $rootScope, $location, $stateParams, $ionicSlideBoxDelegate, $ionicLoading) {
if ($rootScope.userData != undefined) {
$ionicLoading.show({
template: 'loading'
})
$http.get('http://api.getchill.co/api/v1/messages/index/id_user/'+$rootScope.userData.id_user+'/id_contact/'+$stateParams.id)
.success(function(data) {
$scope.messages = data;
for (var i = 0; i < $scope.messages.response.length; ++i) {
if ($scope.messages.response[i].type == 'location') {
var strings = $scope.messages.response[i].content.split(' ');
var lat1 = strings[0], lat2 = strings[1];
$http.get('http://maps.googleapis.com/maps/api/geocode/json?latlng='+lat1+','+lat2+'&sensor=false')
.success(function(data) {
$ionicLoading.hide();
$scope.messages.response[i].address = data.results[0].formatted_address;
});
};
};
$ionicSlideBoxDelegate.update();
});
}
else
{
$location.path('/login');
};
});
$scope.messages.response[i].address
在 success()
函数中未定义。我不明白为什么。
TypeError: Cannot set property 'address' of undefined
at messagesController.js:17
at ionic.bundle.js:17151
at processQueue (ionic.bundle.js:20962)
at ionic.bundle.js:20978
at Scope.$eval (ionic.bundle.js:22178)
at Scope.$digest (ionic.bundle.js:21994)
at Scope.$apply (ionic.bundle.js:22282)
at done (ionic.bundle.js:17439)
at completeRequest (ionic.bundle.js:17629)
at XMLHttpRequest.requestLoaded (ionic.bundle.js:17570)
console.log(数据):_https://dl.dropboxusercontent.com/u/99426050/ShareX/2015/01/2015-01-29_23-40-29.png
最佳答案
这里的问题是,当调用 success 函数时,i
的值发生了变化。 i
现在是数组的长度(因为 for 循环已经结束)。 $scope.messages.response[i]
返回未定义,因为您要求的是最后一个索引之后的索引处的值。这是由于 scoping and closures 的行为造成的.
angular.forEach可以帮助你。
chill.controller('messagesController', function($scope, $http, $rootScope, $location, $stateParams, $ionicSlideBoxDelegate, $ionicLoading) {
if ($rootScope.userData != undefined) {
$ionicLoading.show({
template: 'loading'
})
$http.get('http://api.getchill.co/api/v1/messages/index/id_user/'+$rootScope.userData.id_user+'/id_contact/'+$stateParams.id)
.success(function(data) {
$scope.messages = data;
angular.forEach($scope.messages.response, function(response, i){
if (response.type == 'location') {
var strings = response.content.split(' ');
var lat1 = strings[0], lat2 = strings[1];
$http.get('http://maps.googleapis.com/maps/api/geocode/json?latlng='+lat1+','+lat2+'&sensor=false')
.success(function(data) {
$ionicLoading.hide();
response.address = data.results[0].formatted_address;
});
};
});
$ionicSlideBoxDelegate.update();
});
}
else
{
$location.path('/login');
};
});
关于javascript - 在方法中看不到对象数组。 ( Angular ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28223569/