I have currently been building a CRUD application in a MEAN stack. But I have encountered a potential issue I cannot seem to solve.
A brief overview is I have a number of blog posts and want basic pagination to load more posts on an ng-click event (based off the _id) I can fetch the data but im having an issue updating the $scope with the newly fetched objects.
Load More Posts HTML:
<div ng-click="loadMoreBlogPosts(post._id)" ng-show="$last">Load more</div>
Within my Angular Controller:
// All Blog Posts (This works fine)
$scope.allPosts = function() {
$scope.posts = Blog.Posts.query();
}
// Load More Blog Posts
$scope.loadMorePosts = function(id) {
/* Current Issue */
Blog.MorePosts.query({id:id}, function(data) {
$scope.posts.push(data) /* This doesn't work */
})
}
Angular Model:
return {
Posts: $resource('/api/blog', {}, {
query: { method: 'GET', isArray: true },
add: { method:'POST', isArray:false },
}),
MorePosts : $resource('/api/moreposts/:id', {}, {
query: { method: 'GET', isArray: true, params:{ id:'@id' } }
}),
Post: $resource('/api/blog/post/:id', {}, {
query: { method: 'GET', isArray: true, params:{ id:'@id' } },
add: { method:'POST', isArray:false },
update: { method:'PUT', isArray:false, params:{ id:'@id' } },
delete: { method:'DELETE', params:{ id:'@id' } }
}),
}
Mongoose/MongoDB/Node Controller:
exports.posts = function(req, res, next) {
// Blog Posts
Blog.find()
.sort('-created')
.limit(3)
.find(function (err, posts) {
// Check
if(err) {
// Error
return next(err)
} else {
// Success
res.json(posts)
}
})
};
exports.moreposts = function(req, res, next) {
//console.log(req.params.id);
// Blog Posts
Blog.find({"_id": { "$lt": req.params.id }})
.sort('-created')
.limit(2)
.find(function (err, posts) {
// Check
if(err) {
// Error
return next(err)
} else {
// Success
res.json(posts)
console.log(posts);/* Showing in Terminal */
}
})
};
This has been perplexing me for a few hours now. Im certain I must be overlooking something rather simple, or that in-fact my logic is entirely incorrect (I hope its the former) Any help or guidance would be appreciated.
On a side note, if the loadMoreBlogPosts function is fired, with the following:
$scope.posts = Blog.MorePosts.query({id:id})
The above will show change the $scope.posts to show the objects returned from the Node/mongo controller. This shows that the logic is fine, I just still need to find a way to append the data to $scope.posts, not replace it.