2015-04-07 63 views
1

我正在嘗試學習Angular並編寫了下面的代碼來查找我的IP。我可以輕鬆地訪問並將IP打印到SUCCESS內部的控制檯,但無法在GET方法之外訪問它。即使在SUCCESS中設置變量來響應也沒有工作。任何幫助將不勝感激。Angular:訪問成功響應

 var app = angular.module('myApp', []); 

     var ip; 

     app.controller('customersCtrl', function($scope, $http) { 
      console.log("Console Works"); 


      $http.get("https://api.ipify.org/") 
      .success(function (response) { 
       console.log("Success " + response); 
       ip = response; 
       console.log("IP Inside: " + ip); 
      }); 
     }); 
     console.log("IP Outside: " + ip); 

控制檯打印:

IP外:未定義

控制檯作品

成功11.222.222.11

裏面的IP:11.222.222.11

+0

的可能重複[如何返回從異步調用的響應?](http://stackoverflow.com/questions/14220321/how-to-return-異步調用響應) –

回答

0

其因Java類cript是異步的。所以console.log("IP Outside: " + ip);在成功響應之前被調用。所以如果你想在IP上執行一些任務,那麼成功的方法就是這樣。

1

這就是我們所說的異步世界。

$ http.get發送異步調用並等待您的承諾的回調(成功或錯誤)語句console.log(「IP Inside:」+ ip);外部已經執行,但你仍然沒有任何價值。

您可以訪問varable外面像

 var app = angular.module('myApp', []); 

      var ip; 

      app.controller('customersCtrl', function($scope, $http) { 
       console.log("Console Works"); 
       $scope.ip=""; 

       $http.get("https://api.ipify.org/") 
       .success(function (response) { 
        console.log("Success " + response); 
        $scope.ip = response; 
        console.log("IP Inside: " + $scope.ip); 
       }); 
      }); 
     $scope.$watch('ip',funciton(newVal){ 
       console.log(newVal); // It is new value of your IP 
      ip=newVal; 
     }); 
+0

使用上面的代碼,我得到$ scope沒有定義在第3行上 $ scope.ip =「」; – JungleJeem

+0

嘿,我更新了我的答案:) – squiroid

+0

感謝您的快速回復。我仍然無法讓你的代碼工作。 $ scope。$ watch('ip',funciton(newVal){==>意外的標記{ – JungleJeem