Ciel
Ciel

Reputation: 4440

angularjs - getting the element that is clicked

I have a situation where I want to determine a bit about something that is clicked; Basically here is the layout.

<div ng-controller="DropDownController">
   <div class="dropdown-menu" ng-click="check($event)">
      <div class="container">
         <div>
            // lots of other content and layers
            <a href="#">This is somewhere in there</a>
         </div>
      </div>
  </div>

So then on the controller, it's very simple.

Basically, if the user clicks a hyperlink, it'll work as expected. But if they click anything else on the layer, it just ignores the click completely. I'm having a hard time figuring out how to determine if a link was clicked though.

app.controller("DropDownController", function($scope){
   $scope.check = function($event){
      // if the clicked target is an <a>, then proceed
   $event.preventDefault(); // should never reach this, if a link is clicked.
   $event.stopPropagation(); // should never reach this, if a link is clicked.
});

Update

I've been able to detect the element using $event.target.localName !== 'a', but this feels a bit hacky. I'm not sure what localName is, or how reliable it is. Is this a good surefire way to make sure it only reacts to an anchor? Or at the very least, something that I have demarcated as clickable?

Upvotes: 1

Views: 1601

Answers (1)

akskap
akskap

Reputation: 823

You can track the $event.target.tagName property to find out if an anchor tag has been clicked, and this is standard. So you can be sure about this working in all scenarios.

if ($event.target.tagName === 'A') {
   alert('Link clicked');
}
else{
 //Do something else
}

I have created a JSFiddle for you. Should clear the concept:

http://jsfiddle.net/8KJ4Y/1/

Upvotes: 3

Related Questions