[英]An array of objects can not be seen in the method. (angularjs)
对不起我的英语不好。
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
这里的问题是,调用成功函数时, i
的值已更改。 i
现在是数组的长度(因为for循环已结束)。 $scope.messages.response[i]
返回未定义,因为您要在最后一个索引之后的索引处输入值。 这是由于作用域和闭包的行为。
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');
};
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.