Gaurav Aggarwal Gaurav Aggarwal - 1 month ago 7
Javascript Question

Angularjs issue in getting id of clicked element

I am trying to get id of the clicked element in angularjs and it is working quite fine. Below is my code

html

<a href="#faqinner/contactform" class="clearfix" ng-click="getCateId($event)" id="{{option.id}}">
<span class="icon">
<img ng-if="option.icon!=null" ng-src="http://images.crownit.in/others/{{option.icon}}">
<img ng-if="option.icon==null" ng-src="https://crownit.in/wp-content/themes/crownit-theme/images/faq_default_icon.png">
</span>
<span class="faq_name">{{option.name}}</span>
<span class="arrow">
<img src="images/right_arrow.png">
</span>
</a>


controller

$scope.getCateId = function(obj, $event){
$rootScope.cateId = obj.target.id;
console.log($rootScope.cateId);
};


The above code should return the id of the clicked
<a>
tag but the problem i am facing is there is more
<span>
in
<a>
tag so when i click on the space of span it target's the
<span>
tag which has no id but when i specifically click on the top free space where no inner
<span>
covered then it works fine.

How can i get the id of
<a>
even if i click on
<span>
space??

Answer

You just need to pass the option.id to ngClick handler

<a  ng-click="getCateId(option.id)" id="{{option.id}}">

controller method

$scope.getCateId = function(optionId){
    console.log(optionId);
};