I might be totally confused on how to properly use callback methods for ajax calls in angular. I have the following angular app and cannot figure out how to display the testUser object only after the ajax call is successfully completed.
I have an ng controller like so:
Controllers.controller('mainController', ['$scope','UserService', function ($scope, UserService) {
...
$scope.testUser = UserService.getTestUser();
...
}
The UserService is defined like so:
Services.service('UserService', function () {
...
this.getTestUser = function() {
...
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
return JSON.parse(xmlhttp.responseText);
}
};
xmlhttp.open('GET',url,false); //async set to false
xmlhttp.send();
}
...
}
Currently, the $scope.testUser is 'undefined' and blank on the page because it is being displayed before the ajax call completes. You can see in my service function that I have async set to false, but it doesnt seem to matter.
I've confirmed the ajax call does eventually return a populated user object. What am I missing to make the page display $scope.testUser only when its been successfully retrieved?
$httpservice to do XHRs. docs.angularjs.org/api/ng/service/$http