46

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

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

如果那样,我如何获取数据/信息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');

            }
         };
4

4 回答 4

49

正确的解决方案是将 id 作为参数传递给删除函数,例如

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

然后

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

        }
     };

不应该这样做,而只是为了演示

在里面ng-click你可以使用 获取事件$event,所以

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

然后

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

演示:小提琴

于 2013-12-28T12:16:49.130 回答
4

访问单击的链接标签属性

jQuery中,

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

点击上面的链接被处理为

$('.test').click(function(){
   console.log($(this).attr('data-id')); 
});

jQuery 的演示代码:小提琴

Angularjs中,

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

点击上面的链接被处理为

$scope.delete = function (e) {
    console.log($(e.currentTarget).attr("data-id")); 
 }

Angularjs 的演示代码:小提琴

于 2015-05-05T09:19:53.407 回答
2

您还可以使用以下方法以角度访问 Jquery 的事件数据:

  $scope.myClickedEvent = function(clickEvent) {
    $scope.clickEvent = simpleKeys(clickEvent);
    angular.element(clickEvent.currentTarget);
    console.log(angular.element(clickEvent.currentTarget).text());
   /*
   * return a copy of an object with only non-object keys
   * we need this to avoid circular references
   */
   function simpleKeys (original) {
    return Object.keys(original).reduce(function (obj, key) {
      obj[key] = typeof original[key] === 'object' ? '{ ... }' : original[key];
      return obj;
    }, {});
  }
};

您单击的元素应包含这样的 ng-click

ng-click="myClickedEvent($event)"
于 2016-02-08T10:36:33.757 回答
0

如果出于其他原因,您仍然需要访问该元素,我就是这样做的:

<span ng-click="selectText($event)"></span>

并在控制器中

$scope.selectText = function(event) {
  var element = event.currentTarget; // returns the span DOM Element
  // Now you can access its dataset just like in plain old JS
  // In my case it was for selecting the content of a tag on click anywhere on the tag
};
于 2016-11-09T15:08:43.607 回答