Angularjs ng-click:如何获得这个数据?
比方说,我有这个项目在angular度ng-click
事件的列表中。
<a data-id='102' ng-click='delete()'>Delete</a>
那么如何获得数据/信息呢?
$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'); } };
正确的解决办法是将id作为parameter passing给delete函数
<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
来获取$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 };
演示: 小提琴
您还可以使用以下命令以angular度访问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)"
访问点击链接标签属性
在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的演示代码: 小提琴
如果由于其他原因,你仍然需要访问这里的元素是如何做到的:
<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 };