I have attempted to create a lazy loading solution for my posts, see below:
$scope.loadMore = function() {
if(hasRunBefore===0){
page+=1;
}
if($scope.postsCount > $scope.posts.length){
$http.get('/api/posts', {params: { page: page, pageSize: 10 }})
.then(function(res){
var morePosts = res.data.posts;
if(morePosts && morePosts.length > 0){
loadData(morePosts);
page+=1;
hasRunBefore+=1;
}
});
}
};
};
var loadData = function(posts){
$scope.posts = $scope.posts.concat(posts);
};
Some notes:
$scope.postsCountis grabbed by getting the length of the whole table in Mongo, say this is 50 in this case$scope.loadMoreis called whenever you reach the end of a page on the frontend (infinite-scrollis anyone's interested)$scope.loadMorecan be called multiple times as it is triggered when you reach the end of a page
The problem is - loadData() is the function that appends to the $scope.posts, so the if($scope.postsCount > $scope.posts.length) is always true
Question - I am new to the promise approach in Angular 1.6.x, i.e.: .then. How will I need to restructure this so that I wait for the loadData() to finish executing so that the if($scope.postsCount > $scope.posts.length) can be accurate?
callbackfunction where$scope.posts.lengthcould be evaluated.