如何在AngularJS中确定方法的范围

时间:2015-03-06 23:52:41

标签: angularjs function controller

我有这个控制器有几个相互调用的功能。成功之后,我想返回要显示的内容(位于最后一个函数中)。出于某种原因,没有错误,返回不起作用,但console.log是。有人可以告诉我为什么退货不起作用,请给我一个解决方案。非常感谢!

.controller("dayController", function(){

  .controller("weatherController", function(){

    this.currentWeatherToDisplay = function(){
      if(navigator.geolocation){
        navigator.geolocation.getCurrentPosition(gotLocation,initialize);
      }
      else{
        alert("Device does not support geolocation");
        initialize();
      }

    };


    var currentLocation;

    //get the location coords
    function gotLocation(pos){
      var crd = pos.coords;
      currentLocation = loadWeather(crd.latitude+','+crd.longitude);
      initialize();
    }

    function initialize(){
      if(!currentLocation){
        loadWeather("Washington, DC");
      }

      else{
        loadWeather(currentLocation);
      }
    }


    function loadWeather(location){
      $.simpleWeather({
        location: location,
        woeid: '',
        unit: 'f',
        success: function(weather) {
          var html = weather.temp+'°'+weather.units.temp;
          console.log(html);
          return html;

        },
        error: function(error) {
          console.log(error);
          return error;
        }
      });
    }
  });

1 个答案:

答案 0 :(得分:0)

嗯,mmmm你使用一些jQuery插件来获取当前位置的天气,并且几乎每个jQuery插件都使用回调调用工作(成功和错误)首先我建议你将这个方法重写为某个东西像这样:

function loadWeather(location){
  var defered = $q.defer();
  $.simpleWeather({
    location: location,
    woeid: '',
    unit: 'f',
    success: function(weather) {
      var html = weather.temp+'°'+weather.units.temp;
      console.log(html);
      defered.resolve(html);

    },
    error: function(error) {
      console.log(error);
      defered.reject(error);
    }
  });
  return defered.promise;
} 

此外,您必须将$ q依赖项注入控制器,如下所示:

module.controller("weatherController", function($q){...}

或者

module.controller("weatherController", ['$q',function($q){...}

我建议最后通过minyfication改进angular,当你返回一个类似函数 loadWeather 的承诺时,你必须理解关于$ q(基于kriskoval Q库)的一些基本原则,一个承诺是一个未来的预期值,有一个方法然后来处理该数据(这是一个非常简短的概念),这意味着:

 function gotLocation(pos){
  var crd = pos.coords;
  loadWeather(crd.latitude+','+crd.longitude)
    .then(function(html){
      //html contain the expected html from loadWeather defered.resolve(html)
      currentLocation = html;
    })
    .catch(function(error){
      //error contain the expected error by execute defered.reject(error)
      // maybe gonna try to initialize here
      initialize();
    })

 }

这必须有效,请记住将初始化函数更改为以下内容:

 function initialize(){
   var promise;
  if(!currentLocation){
    promise = loadWeather("Washington, DC");
  }

  else{
    promise = loadWeather(currentLocation);
  }
  promise.then(function(html){
    // some logic with succesful call
  }, function(error) {
    // some logic with error call
  })
}