在AngularJS获取点击的元素的ID [英] Obtaining clicked element's ID in AngularJS

查看:2321
本文介绍了在AngularJS获取点击的元素的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的角器看起来是这样的:

My Angular controller looks like this:

angular.module('spark')
    .controller('MainCtrl', ['$scope', '$location', function ($scope,$location) {
        $scope.handleThisElement = function (event) {
            alert(event.target.id);
        }
        $scope.changeView = function(view){
            $location.path(view);
        }
    }]);

我的HTML如下:

My HTML looks like this:

<a id="testID" href="" ng-click="handleThisElement($event); changeView('panel3')">
...
</a>

该警报的应用路线有不同的看法,这就是我想要的东西之前弹出。但是,当它出现时,警告框为空。我怎样才能得到它读取被点击链接的id(即'testID')?

The alert pops up before the application routes to a different view, which is what I want. But when it comes up, the alert box is empty. How can I get it to read the id of the clicked link (i.e. 'testID')?

推荐答案

就张贴作为一个快速的回答,您可以使用event.currentTarget而不是event.target,以获得绑定登记的元素。在这种情况下,NG-点击绑定到元素应用它,所以你应该得到这个元素。正如评论所说,这是一个非典型的路要走,因为它联系在一起的控制器来这意味着控制器不能测试或使用独立于特定的DOM(可测性断裂)。

Just posting as a quick answer you can use event.currentTarget instead of event.target in order to get the element the binding was registered on. In this case the ng-click binds to the element you apply it to so you should get that element. As mentioned in the comments this is an atypical way to go as it ties the Controller to the DOM which means the Controller can't be tested or used independent of a particular DOM (breaks testability).

这篇关于在AngularJS获取点击的元素的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆