范围变量AngularJS

问题描述:

我有一个关于Cordova程序中变量范围的问题。范围变量AngularJS

这是我的代码:

angular.module('starter.services', []) 

.factory('myFactory', function ($http) { 
     var myVar = "HELLO"; 
     alert(myVar); //HELLO -> Correct 

     $http.get("URL").then(
      function (response) { 
       myVar = response.data; 
       alert(myVar) // Correct Answer 
      }, function (error) { 
       console.log("Get config.json error - " + JSON.stringify(error)); 
      } 
     ); 
     alert(serverName); //HELLO -> why? 

我宣布我的HTTP块外部变量。你可以帮我吗?谢谢

+0

可能想再次检查该代码。 'alert(serverName)'会给出未定义的代码,上面显示的代码。 –

其中之一,你从来没有定义serverName,这样将提醒未定义。

您的最终警报也在您的$http.get()已返回之前被调用,因此myVar尚未更新。我想你应该阅读$http服务(https://docs.angularjs.org/api/ng/service/ $ http)以及承诺如何工作(http://andyshora.com/promises-angularjs-explained-as-cartoon.html)。