I have a page that shows blog posts. I am trying to pass a delete function through ng-click. However, when I click on the hyperlink (ng-click), it does not call that function from the controller. Controller is properly loaded and I used a console.log to ensure that the page is successfully loading the controller in question. Any ideas? Thank you all!
HTML w/ng-click (about.html):
<table class="table table-bordered table-striped" ng-show="post.posts">
<thead>
<tr>
<th>_id</th>
<th>Title</th>
<th>Body</th>
<th>Created</th>
<th>Updated</th>
<th class="col-sm-2"></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="post in post.posts | orderBy: 'createdAt'">
<td>{{ post._id }}</td>
<td>{{ post.title }}</td>
<td>{{ post.body }}</td>
<td>{{ post.createdAt | date : "MMMM d, y h:mm a" }}</td>
<td>{{ post.updatedAt | date : "MMMM d, y h:mm a" }}</td>
<td class="col-sm-2">
<a ng-href="/about/{{ post._id }}" class="btn btn-danger">Edit</a>
<!-- ============================
DELETE BUTTON THAT IS NOT WORKING
--> =============================
<a ng-href="#" ng-click="post.deletePost(post._id)" class="btn btn-primary">Delete</a>
</td>
</tr>
</tbody>
</table>
Controller:
angular.module('postCtrl', [])
.controller('postController', function(Post) {
var vm = this;
// grab all posts at page load
Post.all()
.success(function(data) {
// bind the posts that come back to vm.posts
vm.posts = data;
});
// =============================
// FUNCTION I ATTEMPTING TO CALL
// ==============================
vm.deletePost = function(id) {
Post.delete(id)
.success(function(data) {
// get all posts to update the table
Post.all()
.success(function(data) {
vm.posts = data;
});
});
};
});
API Endpoint (tested with postman, properly working):
// DELETE request to delete a post by ID
apiRouter.route('/posts/:post_id')
// delete the user with this id
.delete(function(req, res) {
Post.remove({
_id: req.params.post_id
}, function(err, post) {
if (err) res.json({ message: "Error: " + err});
res.json({ message: 'Successfully deleted' });
});
});
Angular Route:
.when('/about', {
templateUrl: 'app/views/pages/posts/about.html',
controller: 'postController',
controllerAs: 'post'
});