回调函数没有保持局部变量值

时间:2016-03-19 20:04:07

标签: javascript angularjs function

我可能会严重违反我的条款,所以如果你知道正确的方式来引用价值' a'在像以下的函数中:

var a = 10;
function addA(b){
  return b + a;
}

让我知道。

无论如何,长话短说,我想在回调返回后用值修改$ scope内的变量。这就是我正在做的事情:

function fetchFromAPIs(_scope){
  if (navigator.geolocation){

    var foo = function(position){
      var scope = _scope;
      getPosition(position, scope);
    }
    navigator.geolocation.getCurrentPosition(foo);
  }
  else{
    $(body).prepend("<span>Geolocation is not supported by this browser.</span>");
  }
}

function getPosition(position, scope){
  scope.weather = 'foo';
  scope.latitude = position.coords.latitude;
  scope.longitude = position.coords.longitude;
  getCityCountry(scope);
  getWeather(scope);
}

angular.module('app', [])
.controller('weatherController', function($scope){

  function init(){
    fetchFromAPIs($scope);
  }

  init();
});

然而,$ scope.weather没有得到更新。但是如果我在getPosition中注释掉需要的位置,并在fetchFromAPIs($ scope)中调用foo(&#39;&#39;),则$ scope.weather值会更新。

究竟发生了什么?是否有更好的Angular批准的方法来做到这一点?考虑放弃并仅使用jQuery在页面上设置我的获取值......

1 个答案:

答案 0 :(得分:-1)

我相信你的问题是

var foo = function(position){
  var scope = _scope;
  getPosition(position, scope);
}

将其更改为:

var foo = function(position){
   scope = _scope; //reference global variable and not local.
  getPosition(position, scope);
}