Angularjs ng-click:如何获得`this`数据?

lau*_*kok 41 jquery onclick angularjs jquery-1.9

假设我在带有角度ng-click事件的列表中有这个项目.

<a data-id='102' ng-click='delete()'>Delete</a>
Run Code Online (Sandbox Code Playgroud)

如果this那么我如何获得数据/信息?

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

            }
         };
Run Code Online (Sandbox Code Playgroud)

Aru*_*hny 48

正确的解决方案是将id作为参数传递给delete函数

<a data-id='102' ng-click='delete(102)'>Delete</a>
Run Code Online (Sandbox Code Playgroud)

然后

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

        }
     };
Run Code Online (Sandbox Code Playgroud)

这不应该做,只是为了证明

在里面ng-click你可以使用$event,所以

<a data-id='102' ng-click='delete($event)'>Delete</a>
Run Code Online (Sandbox Code Playgroud)

然后

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

演示:小提琴

  • 谢谢,我正在寻找这个答案.但为什么不使用$ event? (4认同)