Vercingetorix
Vercingetorix

Reputation: 263

Obtaining clicked element's ID in AngularJS

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);
        }
    }]);

My HTML looks like this:

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

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')?

Upvotes: 0

Views: 354

Answers (1)

shaunhusain
shaunhusain

Reputation: 19748

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).

Upvotes: 1

Related Questions