basagabi
basagabi

Reputation: 5064

angularjs get previous element of clicked button inside ng-repeat

How do you get the previous element of the clicked element that is inside a ng-repeat using AngularJS? In jquery, this could be done using $(this).prev() or something equivalent.

For an instance I have this:

<table class="table table-striped" ng-controller="UserController as vm">
    <tr ng-repeat="(key, value) in vm.users">
        <td>{{value.username}}</td>
        <td><button name="btnDelete" id="btnDelete" class="btn btn-danger" ng-click="vm.delete(key)">Delete</button></td>
    </tr>
</table>

Then on my UserController:

function UserController() {
    var vm = this;
    vm.delete = function(buttonId) {
        // get the clicked element and get previous element
        // "this" doesn't work as it returns the vm itself
    }
}

Thanks in advance!

UPDATE

Should be returning the <td> element of vm.username

Upvotes: 1

Views: 920

Answers (1)

Ramesh Rajendran
Ramesh Rajendran

Reputation: 38683

Try this

ng-click="vm.delete(key,$index)"

and your controller code should be

function UserController() {
    var vm = this;
    vm.delete = function(buttonId,index) {
      if(index > 0){
       var result = vm.users[index-1].username
      }
    }
}

Upvotes: 3

Related Questions