范围变量AngularJS

时间:2017-03-02 17:15:22

标签: angularjs

我对Cordova程序中的变量范围有疑问。

这是我的代码:

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块之外声明了我的变量。你能帮助我吗?谢谢

1 个答案:

答案 0 :(得分:0)

首先,您从未定义serverName,以便提醒未定义。

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

相关问题