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.
console.loglogsundefinedbefore the firstconsole.loglogs the result, right?! That is your problem. Timing! Not scope..then()$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 havengRouteorui.routerfor routing.