0

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);
        })

    }
}
}]);
1

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the explanation. That makes a lot more sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.