Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - Remove table row after object destroyed

I have an AngularJS app that returns a list of json objects and I iterate through those objects and place them into a table.

Each item on the table has a "Delete" button with an ng-click method:

<td><a ng-click="testButton()" class="btn btn-danger btn-mini">Delete</a></td>

I am using ng-resource to delete the object - and that works fine.

However, I want to also be able to hide (or remove) the row that houses the object and the delete button after it is deleted - preferably by using JQuery.

Here is my destroy method:

$scope.destroyThing = function() {
        $scope.thing= this.thing;
        $scope.thing.$destroy();
        $(this.thing).closest("tr").hide(); // something like this maybe
    }

The method destroys the object just fine - it just doesn't remove the row... so I tried logging the object returned when I click the button:

$scope.testButton = function() {
        console.log(this);
    }

That seems to return the angular Scope object itself - but I can't find a way to access any of the DOM elements that it relates to.

Here is a screenshot to show you the object returned from the testButton function - which is triggered by clicking the button of course:

enter image description here

How can I access DOM elements related to the Angular object with JQuery?

EDIT

Here is the complete table row:

<tr ng-repeat="franchise in franchises">
                <td ng-model="franchiseName">{{franchise.franchise_name}}</td>
                <td ng-model="franchiseNumber">{{franchise.franchise_number}}</td>
                <td><a class="btn btn-mini">Edit</a></td>
                <td><a ng-click="destroyFranchise()" class="btn btn-danger btn-mini">Delete</a></td>

            </tr>
like image 564
PhillipKregg Avatar asked May 24 '12 19:05

PhillipKregg


2 Answers

You don't want to access the DOM from the controller. That's against the Zen of Angular :-D

Use ng-hide directive:

<td><a ng-click="hide()" ng-hide="isHidden">Delete</a></td>

And the controller just change the model value, that ng-hide is bound to (in this case isHidden property).

How do you populate the table ? Are you using ng-repeat ? If so, it's enough to just remove the item from the collection that ng-repeat repeats over and the DOM will be updated automatically.

Check out http://www.youtube.com/watch?v=WuiHuZq_cg4

like image 91
Vojta Avatar answered Oct 02 '22 17:10

Vojta


While messing directly with the DOM is not the Angular way, for the people coming from Google that still need to do this, to pass the DOM element to an existing jQuery plugin or something:

  1. Use Angular-UI's jQuery Passthrough (recommended)
  2. Write an Angular directive and wrap the DOM handling in there. A starting point: jsfiddle.
like image 41
mb21 Avatar answered Oct 02 '22 16:10

mb21