Reputation: 967
I want to use $scope.posts.splice(post, 1);
to remove an object (post) of an ng-repeat.
When I click on the delete button, the wrong post gets deleted (always the first one). When I refresh the browser, the right post was deleted (api delete function works).
HTML:
<div ng-repeat="post in posts | orderBy: '-upvotes'">
<md-button class="md-icon-button md-accent" aria-label="Vote-Up" ng-click="incrementUpvotes(post)">
<i class="material-icons">thumb_up</i>
</md-button>
{{post.upvotes}}
<span style="font-size:20px; margin-left:10px;">
<a ng-show="post.link" href="{{post.link}}">
{{post.title}}
</a>
<span ng-hide="post.link">
{{post.title}}
</span>
</span>
<span>
posted by <a ng-href="#/users/{{post.user.username}}">{{post.user.username}}</a>
<span>
<a href="#/posts/{{post.id}}">Comments</a>
<a href="#" ng-click="deletePost(post)">Delete</a>
</span>
</div>
JS:
angular.module('crud')
.controller('MainCtrl', [
'$scope',
'posts',
'ToastService',
function($scope, posts, ToastService){
$scope.posts = posts.posts;
// Delete Post
$scope.deletePost = function(post){
if(window.confirm('Are you sure?')) {
posts.delete(post).then(function () {
$scope.posts.splice(post, 1);
ToastService.show('Post deleted');
});
}
};
Why does splice remove the wrong post of ng-repeat?
Upvotes: 1
Views: 1016
Reputation: 64657
Because splice
takes the index of the element to delete, not the element itself. You should be able to use indexOf
with it to make it work:
$scope.posts.splice($scope.posts.indexOf(post), 1);
Upvotes: 2
Reputation: 933
You can get the index by passing $index in your function. Its described in the ngRepeat Docs.
<a href="#" ng-click="deletePost($index)">Delete</a>
Upvotes: 0