1

I'm trying to learn Angular and have written the following code to find my IP. I can easily access and print the IP to the console inside SUCCESS but fail to access it outside of the GET method. Even setting the variable to response inside SUCCESS doesn't do job. Any help would be highly appreciated.

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

Console prints:

IP Outside: undefined

Console Works

Success 11.222.222.11

IP Inside: 11.222.222.11

JungleJeem
  • 51
  • 8
  • possible duplicate of [How to return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Naeem Shaikh Apr 07 '15 at 07:44

2 Answers2

1

This is what we called as async world.

$http.get send a async call and waiting for the callback(success or error ) of your promise the statement console.log("IP Inside: " + ip); outside already executed but still you don't have any value in it.

You can access varable outside like

     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;
         }); 
squiroid
  • 13,809
  • 6
  • 47
  • 67
  • With the above code I get $scope is not defined on line 3 $scope.ip=""; – JungleJeem Apr 07 '15 at 07:56
  • Thanks for the quick reply. I still haven't been able to get your code working. $scope.$watch('ip',funciton(newVal){ ==> Unexpected token { – JungleJeem Apr 07 '15 at 08:04
  • You have stated $scope.$swatch outside of the controller, and it returns as unidentified. I have changed you code to include $scope.$watch('ip',function(newVal){console.log(newVal);}); inside the controller, however it returns as a blank line on console – JungleJeem Apr 07 '15 at 08:14
0

Its because javascript is asynchronous. So console.log("IP Outside: " + ip); is called before success response. So if you want to perform some task on IP then do that in success method.

Anita
  • 2,352
  • 2
  • 19
  • 30