我遇到了这个问题。这是我从 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.
});
这是我用 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>
我可以删除我数据库中的帖子,但我不知道如何删除我正在单击的元素。
最佳答案
据我在您的 html 代码中看到的,您有一个变量 $scope.posts.results
。
ng-repeat 为每个元素提供一个变量 $index
,您可以使用它来删除元素
将此 $index
添加到您的 html 中:
ng-click="delete(post, $index)"
然后,在您的 Controller 中,从您的数组中删除该元素
$scope.delete = function($posts, postIndex) {
$http.delete('/api/posts/' + $posts._id)
.success(function(data) {
$scope.posts.results.splice(postIndex, 1);
});
};
然后,ng-repeat 将从 DOM 中删除您的节点。您不需要直接操作 DOM。
关于javascript - 如何删除DOM中的 Angular 生成元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34622078/