在AngularJS中删除错误的ng-repeat对象

时间:2015-10-07 18:52:05

标签: javascript angularjs

我想使用$scope.posts.splice(post, 1);删除ng-repeat的对象(post)。

当我点击删除按钮时,错误的帖子被删除(总是第一个)。刷新浏览器时,删除了正确的帖子(api删除功能正常工作)。

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');
      });
    }
  };

为什么splice会删除错误的ng-repeat帖子?

2 个答案:

答案 0 :(得分:2)

因为splice获取要删除的元素的索引,而不是元素本身。您应该可以使用indexOf来使其正常工作:

$scope.posts.splice($scope.posts.indexOf(post), 1);

答案 1 :(得分:0)

您可以通过在函数中传递$ index来获取索引。它在ngRepeat Docs中描述。

<a href="#" ng-click="deletePost($index)">Delete</a>