如何在函数外部获取数组的值 - Angularjs

时间:2021-06-08 13:38:18

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?

如何访问此函数外的lat和lng变量?

Tku so much

Tku这么多

1 个解决方案

#1


0  

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).

如果你想使用coordenadas(绑定到UI等),你需要将它绑定到$ scope(或被监视的东西)。简单地返回只允许您继续承诺链(您没有这样做)。

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

这样的东西会起作用(在依赖于$ 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:

如果要在其他地方使用返回的promise。然后你将不得不继续链:

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

#1


0  

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).

如果你想使用coordenadas(绑定到UI等),你需要将它绑定到$ scope(或被监视的东西)。简单地返回只允许您继续承诺链(您没有这样做)。

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

这样的东西会起作用(在依赖于$ 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:

如果要在其他地方使用返回的promise。然后你将不得不继续链:

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