Reputation: 286
I have ran into a wall with this. This is my delete function from my mainController.
$scope.delete = function($posts) {
$http.delete('/api/posts/' + $posts._id)
.success(function(data) {
// delete element from DOM
// on success I want to delete the post I'm clicking on.
});
And here is the template where I load my data with angular.
<div id="post-stream">
<h4>Chirp Feed</h4>
<div class="post" ng-repeat="post in posts.results | orderBy:'created_at':true" ng-class-odd="'odd'" ng-class-even="'even'">
<button ng-click="delete(post)" ng-show="authenticated" class="btn btn-danger btn-xs pull-right remove">x</button>
<p>{{post.text}}</p>
<small>Posted by @{{post.created_by}}</small>
<small class="pull-right">{{post.created_at | date:"h:mma 'on' MMM d, y"}}</small>
</div>
</div>
I can delete the posts in my database but I can't figure out how to delete the element I'm clicking on.
Upvotes: 4
Views: 676
Reputation: 286
<button ng-click="delete(post)" ng-show="authenticated" class="btn btn-
This is what I ended up doing.
$scope.delete = function($posts, postIndex) {
$http.delete('/api/posts/' + $posts._id)
.success(function(data) {
var index = $scope.posts.results.indexOf(data);
$scope.posts.results.splice(index, 1);
});
};
Upvotes: 0
Reputation: 11388
As far as I can see in your html code, you have a variable $scope.posts.results
.
ng-repeat gives you on each element a variable $index
that you can use to delete an element
add this $index
into your html :
ng-click="delete(post, $index)"
And then, into your controller, delete the element from your array
$scope.delete = function($posts, postIndex) {
$http.delete('/api/posts/' + $posts._id)
.success(function(data) {
$scope.posts.results.splice(postIndex, 1);
});
};
then, ng-repeat will remove your node from the DOM. You don't need to manipulate the DOM directly.
Upvotes: 3