4

I have ran into a wall with this. 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 load my data with 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 the posts in my database but I can't figure out how to delete the element I'm clicking on.

3
  • you would just want to remove the post from your post.results collection. That will automatically remove it from the dom. Commented Jan 5, 2016 at 22:10
  • If you try to manipulate the dom directly you are usually doing something wrong with angular. Commented Jan 5, 2016 at 22:11
  • That's what it does right now but I would have to reload the page to see the changes. I want to delete the element on click. Commented Jan 5, 2016 at 22:12

2 Answers 2

3

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

ng-repeat gives you on each element a variable $index that you can use to delete an element

add this $index into your html :

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

And then, into your controller, delete 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);
          });

};

then, ng-repeat will remove your node from the DOM. You don't need to manipulate the DOM directly.

Sign up to request clarification or add additional context in comments.

2 Comments

awesome!!!! it worked. I have to wait 3 minutes at this time before I can check your solution. Thank you!
Thanks to you too, I didn't know about ng-class-odd="'odd'".
0
<button ng-click="delete(post)" ng-show="authenticated" class="btn btn-

This is what I ended up doing.

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

    };

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.