I am new to angular and trying to integrate it within my application. I am attempting to use a simple $http.get
to a .JSON file, which seems to be found, but when trying to pass the data to the front end, or even alert it, is it alerting as []
Here my get:
$scope.countries = [];
$http.get('/resources/data/countries-report.json', function(data){
$scope.countries = data;
}, function(error) {
//handle error here
});
alert(JSON.stringify($scope.countries));
Here's my .JSON file:
{
"firstName" : "Joe",
"surName" : "Bloggs",
"countries" : [
{ "name": "France", "population": "63.1" },
{ "name": "Span", "population": "52.3" },
{ "name": "United Kingdom", "population": "61.8" }
]
}
$http.get is an async function. when you try
alert(JSON.stringify($scope.countries));
$scope.countries is equals to []. You must wait for server response before using data.Try to do your alert into success function
Try this:
Alert should go in the callback.
This should do it
also this equivalent would work
Edit --
Instead of $http.get('/someUrl', sucessCallback, errorCallback) it should be either
or
see docs
Because $http.get is asynchronous alert should be moved in the successCallback function, to ensure that
$scope.countries=data
is executed before calling alert.