【发布时间】:2014-08-18 12:53:49
【问题描述】:
我正在尝试通过 http 请求方法将数据存储到 location[] 数组到 json 文件中。
问题是我的列表控制器总是包含一个空数组。
我的工厂
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;
}
};
});
我的控制器
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 **
});
我似乎无法弄清楚为什么我的$scope.locations = [] 仍然是空的
【问题讨论】:
-
你填写
$scope.locations,你打印$scope.geoLocations的长度。 -
您的
listing__data.makeRequest是Deferred anti-pattern 的一个示例。$http.get已经返回了一个承诺,所以不需要延迟:return $http.get(...).then(function (resp) { return resp.data; }); -
@JBNizet 原谅错字,正在重构代码以粘贴到这里
标签: angularjs