Search code examples
angularjsangularjs-scope

AngularJS: Accessing an object nested within $scope


I have been trying to resolve this issue with no success. I understand that getCurrentPosition() returns a promise and calling $scope.map.center within the .then() function will work. I also understand that $scope runs in the digest cycle and its properties and objects are updated when the promise resolves. I am new to all this and I hope I am making sense.

That said, I would totally love to understand what's going on because console.log($scope.map) works as expected, {{ map.center }} displays as expected, but console.log(map.center) returns an empty object outside of the .then() function.

Thanks in advance for your assistance!

    $scope.map = {
            control: {},
            center: {},
            zoom: 16
        };

    $geolocation.getCurrentPosition({
        timeout: 60000,
        maximumAge: 250,
        enableHighAccuracy: true
    }).then(function(position) {
        $scope.map.center.latitude = position.coords.latitude;
        $scope.map.center.longitude = position.coords.longitude;
    });


    //Output
    
    console.log($scope.map); //returns full object including data within $scope.map.center

    console.log($scope.map.center); //returns an empty object. I am looking to convert this to an array using lodash. 
 {{ map.center  }} works fine and returns the coordinates of my current location

**Edit (Uploaded image of console) **

This is what I see in the console. First object is $scope.map Second object is $scope.map.center


Solution

  • The then function is called when getCurrentPosition has finished (it's asynchronous) and sent the data back to the client. It's the only place you can reliably access the data retrieved by it. If you are making asynchronous calls you must use the then function to access the data. THEN is what takes place after the call is made. The code that follows the then (outside of the function) executes immediately after getCurrentPosition is called - not when it's completed.

    You can call another function outside from the then function and pass the position object to it if you're simply looking for a different place to put this code.

    $scope.map = {
            control: {},
            center: {},
            zoom: 16
        };
    
    $geolocation.getCurrentPosition({
        timeout: 60000,
        maximumAge: 250,
        enableHighAccuracy: true
    }).then( processMap(position))
    
    function processMap(position) {
        $scope.map.center.latitude = position.coords.latitude;
        $scope.map.center.longitude = position.coords.longitude;
        console.log($scope.map); 
        console.log($scope.map.center); 
    };
    

    If you are looking for more information about asynchonous calls, see this explanation:

    http://docs.apigee.com/api-baas/asynchronous-vs-synchronous-calls