gpt4 book ai didi

javascript - 拼接删除 AngularJS 中 ng-repeat 的错误对象

转载 作者:行者123 更新时间:2023-11-30 16:33:32 27 4
gpt4 key购买 nike

我想使用 $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的错帖?

最佳答案

因为 splice 获取要删除的元素的索引,而不是元素本身。你应该能够使用 indexOf 来让它工作:

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

关于javascript - 拼接删除 AngularJS 中 ng-repeat 的错误对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33000204/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com