angularjs - Angular Factory data empty after $http -


i'm trying store data location[] array via http request method json file.

the problem listings controller contains empty array.

my factory

app.factory('listing__data', function($http, $q){   return {     locations: '',     makerequest: function(url) {       // create deffered object       var deferred = $q.defer();        $http.get('/'+url).then(function(resp) {         deferred.resolve(resp.data);       });       return deferred.promise;     },     geturl: function(params) {       var url = "locations.json";        if(!this.locations) {         this.locations = this.makerequest(url);       }       // return myobject stored on service       return this.locations;     }   }; }); 

my controller

var listings__controller = app.controller('listings__controller', function($scope, distance__service, listing__data) {     $scope.locations = [];      listing__data.geturl(distance__service.meters).then(function(data) {     $.each(data.listings, function(i, item) {           $scope.locations.push(item.location);           console.log(item.location); // ** shows correct object **         });     });     console.log("how many inside:"+$scope.locations.length); // ** empty - shows 0 ** }); 

i can't seem figure out why $scope.locations = [] remains empty

even without typo jb nizet mentioned, still see 0, because console.log("how many inside:"+$scope.locations.length); gets executed before callback pass listing__data.geturl(distance__service.meters).then, since latter asynchronous.

remember when using asynchronous functions, flow of execution doesn't follow order of lines of source code.

promise.then(function () {     console.log('inside callback'); }); console.log('outside callback'); 

will print outside callback then inside callback.

consequently, if going use value store inside $scope.locations, have inside callback.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -