Am new to angular. I have tried to get the json response from http get method.
My code is,
app.factory('getdata', function ($http, $q){
this.getlist = function(){
alert('1');
return $http.get('http://www.w3schools.com/angular/customers.php',{'Access-Control-Allow-Origin': 'localhost:*'})
.then(function(response) {
console.log('response'); console.log(response.data); //I get the correct items, all seems ok here
alert('2');
return response.data;
});
}
return this;
});
/* Stream page controller */
app.controller('streamCtrl', function($scope,getdata, $ionicSlideBoxDelegate, $timeout, $ionicScrollDelegate, $location, $sce){
$scope.trustSrc = function(src) {
return $sce.trustAsResourceUrl(src);
}
getdata.getlist()
.then(function(arrItems){
$scope.sliders = arrItems;
});
alert($scope.sliders);
am getting the alert like 1, 'undefined' and 2 but the $scope.sliders has the data. because It was working once I resize the screen and also I can get correct alert inside the
getdata.getlist().then(function(arrItems) {
$scope.sliders = arrItems;
alert($scope.sliders);
});
The reason for getting alert is undefined
is because you haven't define $scope.sliders
in controller and http
request is async so alert($scope.sliders);
function call before getting data
from response and setting that data to $scope.sliders
.
You get alert($scope.sliders);
value only after getting success response.
Other possibility is you can set $scope.sliders = {}
and then use alert($scope.sliders);
which show {}
in alert when then
function is called alert
shows actual response.
Original plunker based on issue
Check comments and updated code in new plunker
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With