在Infinite-scroll工厂下面我用来从后端获取数据,是否有任何地方对这个方法应用$ promise,因为在控制器中我需要知道数据何时加载完毕。
工厂:
app.factory('Gallery', function($http) {
var Gallery = function(media, album_type) {
this.items = [];
this.busy = false;
this.next = '/upload/list/'+ media +'/?album='+album_type+'&page=1';
this.end=false;
};
Gallery.prototype.nextPage = function() {
if (this.busy) return;
this.busy = true;
if (this.next){
var url = this.next;
}
else{
this.end=true;
this.busy = false;
return
}
$http.get(url).success(function(data) {
var items = data.results;
for (var i = 0; i < items.length; i++) {
this.items.push(items[i]);
}
this.next=data.next;
this.busy = false;
if (!data.next)
this.end=true;
this.count=data.count;
}.bind(this));
};
return Gallery;
});
在控制器中;
$scope.images = $scope.images || new ScrollGallery('image', 'CRP');
答案 0 :(得分:0)
我通过在ininite-service中添加$ q来解决问题,$ q返回promise方法。我可以用来检查http是否成功失败。
无限服务::
app.factory('ScrollGallery', function($http,$q) {
var Gallery = function(url) {
this.items = [];
this.busy = false;
this.next = url;
this.end = false;
this.extra = {};
};
Gallery.prototype.nextPage = function() {
var def = $q.defer();
if (this.busy)
return;
this.busy = true;
if (this.next) {
var url = this.next;
} else {
this.end = true;
this.busy = false;
return;
}
$http.get(url).success( function(data) {
var items = data.results;
var extra = [];
if ( typeof data.extra != 'undefined') {
extra = data.extra;
}
for (var i = 0; i < items.length; i++) {
this.items.push(items[i]);
}
this.extra = extra;
this.next = data.next;
this.busy = false;
if (!data.next)
this.end = true;
this.count = data.count;
def.resolve(data);
}.bind(this));
return def.promise;
};
return Gallery;
});
在控制器::
中$scope.mediacontent[$scope.slider_url] =new ScrollGallery($scope.slider_url_pass);
$scope.mediacontent[$scope.slider_url].nextPage().then(function(albums) {
$scope.mediacontent[$scope.slider_url].items[$scope.img_no].active=true;
console.log('albums returned to controller.');
},
function(data) {
console.log('albums retrieval failed.');
});