How to remove angular generated element in DOM

I ran into this wall. This is my delete function from my 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.
        });

And here is the template where I upload my data using 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>

I can delete messages in my database, but I cannot figure out how to delete the item that I click on.

+4
source share
2 answers

As far as I can see in your html code, you have a variable $scope.posts.results.

ng-repeat provides each element with a variable $indexthat you can use to remove the element

add this $indexto your html:

 ng-click="delete(post, $index)"

And then, in your controller, remove the element from your array

$scope.delete = function($posts, postIndex) {    
    $http.delete('/api/posts/' + $posts._id)
          .success(function(data) {
               $scope.posts.results.splice(postIndex, 1);
          });

};

ng-repeat node DOM. DOM.

+3
<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);
              });

    };
0

Source: https://habr.com/ru/post/1622995/


All Articles