2015-03-06 2 views
0

У меня есть этот контроллер, который имеет несколько функций, которые называют друг друга. При успехе я хочу вернуть что-то отображаемое (расположенное в последней функции). По какой-то причине, без ошибок, возврат не работает, но console.log. Может кто-то, пожалуйста, скажите мне, почему возвращение не работает и дайте мне решение, пожалуйста. Спасибо!Как методы области видимости в AnjularJS

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

ответ

0

Ну, мммм вы использовать некоторые 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 улучшения углового, когда вы возвращаетесь обещание как функции loadWeather, вы должны понять некоторые основные принципы, о за $ д (на основе 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 
    }) 
} 
+0

не повезло! Я не понимаю, почему он не возвращает глобальную область действия! – nehas

Смежные вопросы