0

I have a controller and I make an http request to get some data. Data arrives but when I try to use it it's like it does not exist at all. I have used the same method in a previous project and everything worked well. I have been trying to fix this for a couple days but no luck. It seems like there is a problem with the scope or the order of execution is not the right one.

Here is my code:

  .controller("myCtrl", ['$scope', '$http', function($scope, $http) {
    console.log("myCtrl");

    var vm = this;

    $http.get('/get-data').then(function(response) {
      vm.data = JSON.stringify(response.data);
      console.log(vm.data); //returns correct json data
    })

    console.log(vm.data); //returns undefined

  }])

Further information: There are multiple controllers in the module.

5
  • 3
    The second console.log logs undefined before the first console.log logs the result, right?! That is your problem. Timing! Not scope. Commented Oct 26, 2018 at 12:43
  • 1
    It's an asynchronous callback, keep your entire logic inside .then() Commented Oct 26, 2018 at 12:44
  • I can't keep my entire logic inside .then() I have to bind the results to the interface Commented Oct 26, 2018 at 12:54
  • @FotisPapadamis you are already binding it to $scope.data, so you can show it in HTML correctly, but if you need to use it in the controller, then all of your logic has to be within .then(). You can trick it, and make it synchronous with a resolve in app.config, if you have ngRoute or ui.routerfor routing. Commented Oct 26, 2018 at 13:01
  • First console.log is within asynchronous call which means in this scenario it will always be returned after the second console.log because first one takes a bit longer to be displayed. Commented Oct 26, 2018 at 15:45

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.