Reputation: 308
I have a controller where I am trying to store information in $scope.weather and then use it's contents to pass to a function. When I log the result of $scope.weather[0].latitude when I use it one function but when I call it another function within the same controller the result is coming back undefined. Shouldn't the $scope be usable within the same controller? This is also within the same function.
angular.module('CityCtrl', []).controller('CityController', ['$scope', '$http', 'City', function($scope, $http, City){
$scope.update = function (zip) {
City.get({zip : zip}).success(function(response){
$scope.weather = response
}).then(function(response){
$scope.weather = response.data;
// This is returning the expected result
console.log($scope.weather[0].latitude;
})
if(zip.length === 5){
// This is coming back undefined
console.log($scope.weather[0].latitude);
var box = getBoundingBox([$scope.weather[0].latitude, $scope.weather[0].longitude], 50);
City.matches(box[1], box[3], box[0], box[2]).success(function(response){
$scope.matches = response
}).then(function(response){
$scope.matches = response.data;
console.log($scope.matches);
})
}
}
}]);
Upvotes: 0
Views: 285
Reputation: 555
This is an order of operations issue.
When you console.log($scope.weather[0].latitude)
in the if statement $scope.weather
has not actually been set yet because the City.get()
call is asynchronous. This means $scope.weather
will not be set until a successful response is returned from the City service, which in your case will execute after the code block in the if statement.
In order for your if statement code to have access to $scope.weather
you would need to include it in the .then(function() { // if logic here }
portion of your code.
Also it is worth noting that City.get().success()
and City.get().then(successFunction)
are pretty much doing the same thing. You should use one or the other, but you shouldn't need to use both.
Upvotes: 1