Angularjs ng-click: how to get `this` data?

laukok picture laukok · Dec 28, 2013 · Viewed 69.5k times · Source

Let say I have this item in the list with angular ng-click event.

<a data-id='102' ng-click='delete()'>Delete</a>

How can I get the data/ info if this then?

        $scope.delete = function() {

             var id = $(this).attr('data-id');
             console.log(id); // I want to get 102 as the result
             if (confirm('Are you sure to delete?')) {
                $('#contactsGrid tr[data-id="' + id + '"]').hide('slow');

            }
         };

Answer

Arun P Johny picture Arun P Johny · Dec 28, 2013

The right solution will be is to pass the id as an parameter to the delete function like

<a data-id='102' ng-click='delete(102)'>Delete</a>

then

    $scope.delete = function(id) {
         console.log(id); // I want to get 102 as the result
         if (confirm('Are you sure to delete?')) {
            $('#contactsGrid tr[data-id="' + id + '"]').hide('slow');

        }
     };

This should not be done, but just to demonstrate

Inside ng-click you can get the event using $event, so

<a data-id='102' ng-click='delete($event)'>Delete</a>

then

$scope.delete = function (e) {
    var id = $(e.target).data('id');
    console.log(id); // I want to get 102 as the result
};

Demo: Fiddle