2

In jQuery, I can get the element that was clicked in the DOM using the following

$(document).click(function(event) {
    var element = $(event.target);
    console.log(element);
    ....
}

How would I do the same with Angular? I've searched for it online but all of the solutions were related to elements that had an ng-click attribute like links and buttons. I'd like to listen to the click event for the entire DOM and then get the element that was clicked(p, li, a, span etc.) Is there anyway I can achieve this using Angular only or would I have to use jQuery?

2 Answers 2

2

Place the ng-click on the body

 <body ng-click="go($event)">

In your controller:

 $scope.go = function($event){
     alert($event.currentTarget );
 };
Sign up to request clarification or add additional context in comments.

4 Comments

Would you also need to use $event.stopPropagation()?
Potentially on any inner ng-clicks if the detweiller doesn't want the body ng-click triggered
Thanks. If you don't mind me asking, what is this $event.stopPropagation() you speak of? Do I need to use it too?
If you had ng-click="$event.stopPropagation()" on say a button and you clicked the button it would not trigger the body ng-click as well
2

From the docs https://docs.angularjs.org/api/ng/directive/ngClick and https://docs.angularjs.org/guide/expression#-event-:

Event object is available as $event

html

<div ng-click="functionName()"></div>

js

$scope.functionName = function($event){}

1 Comment

Thanks. Apparently, I need to pass the $event as a parameter in functionName() too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.