Javascript 如何在DOM中删除角度生成的元素
我碰到了一堵墙。这是我的主控制器的删除功能Javascript 如何在DOM中删除角度生成的元素,javascript,angularjs,Javascript,Angularjs,我碰到了一堵墙。这是我的主控制器的删除功能 $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.
$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>
啁啾馈源
x
{{post.text}
发布人@{{post.created_by}
{post.created|u在|日期:“h:mma'on'mmmd,y”}
我可以删除数据库中的帖子,但我不知道如何删除我正在单击的元素 就我在html代码中所见,您有一个变量
$scope.posts.results
ng repeat为每个元素提供了一个变量$index
,可用于删除元素
将此$index
添加到html中:
ng-click="delete(post, $index)"
然后,在控制器中,从数组中删除元素
$scope.delete = function($posts, postIndex) {
$http.delete('/api/posts/' + $posts._id)
.success(function(data) {
$scope.posts.results.splice(postIndex, 1);
});
};
然后,ng repeat将从DOM中删除节点。您不需要直接操作DOM。您只需要从post.results集合中删除post。这将自动将其从dom中删除。如果您试图直接操作dom,您通常会在angular上出错。这就是它现在所做的,但我必须重新加载页面才能看到更改。我想在单击时删除元素。太棒了!!!!成功了。现在我必须等3分钟才能检查您的解决方案。非常感谢。也感谢你,我不知道关于
ng class odd=“'odd'”
。
<button ng-click="delete(post)" ng-show="authenticated" class="btn btn-
$scope.delete = function($posts, postIndex) {
$http.delete('/api/posts/' + $posts._id)
.success(function(data) {
var index = $scope.posts.results.indexOf(data);
$scope.posts.results.splice(index, 1);
});
};