I'm trying to store data into a location[] array via http request method to a json file.
The problem is my listings controller always contains an empty array.
My Factory
app.factory('listing__data', function($http, $q){
return {
locations: '',
makeRequest: function(url) {
// Create the 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 the myObject stored on the 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 to figure out why my $scope.locations = [] remains empty
$scope.locations, and you print the length of$scope.geoLocations.listing__data.makeRequestis an example of the Deferred anti-pattern.$http.getalready returns a promise, so there's no need for the deferred:return $http.get(...).then(function (resp) { return resp.data; });