简体   繁体   中英

How can I get the value of array outside the function - Angularjs

I have this function:

  var latLong = promise.then(function(response) {
       for(var j = 0; j <= response.length - 1; j++) {      
            coordenadas.push( {lat: response[j].lat, lng: response[j].lng});   
        }
        return coordenadas;
    });

I got this result

How can I access the lat and lng variables outside this function?

Tku so much

If you want to use coordenadas (binding to UI etc), you need to bind it to $scope (or something being watched). Simply returning only allows you to continue the promise chain (which you are not doing).

Something like this would work (in a controller that depends on $scope ):

    promise.then(function(response) {
       for(var j = 0; j <= response.length - 1; j++) {      
            coordenadas.push( {lat: response[j].lat, lng: response[j].lng});   
        }
        $scope.coordenadas = coordenadas;
    });

If you want to use the returned promise in another place. Then you would have to continue to chain:

var latLong = promise.then(function(response) {
       for(var j = 0; j <= response.length - 1; j++) {      
            coordenadas.push( {lat: response[j].lat, lng: response[j].lng});   
        }
        return coordenadas;
    });

latLong.then(function(coordenadas) {
    console.log(coordenadas;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM