1

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?

1

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

it will find the object with the same reference
yes $scope.posts.splice($scope.posts.indexOf(post), 1); this works perfectly, thank you.
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.