0

I have a problem about the scope of variables in a Cordova program.

This is my code:

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?

I declared my variable outside the http block. Can you help me? thanks

Tân
  • 1
  • 15
  • 56
  • 102

1 Answers1

0

For one, you have never defined serverName so that will alert undefined.

Your final Alert is also being called before your $http.get() has returned, so myVar hasn't been updated. I think you should read up on the $http service (https://docs.angularjs.org/api/ng/service/$http) and how promises work (http://andyshora.com/promises-angularjs-explained-as-cartoon.html).

Matt Brewerton
  • 866
  • 1
  • 6
  • 23