What's the equivalent of the .closest jQuery function in AngularJs?

I am trying to implement a custom popup in Angular. The problem is when clicking outside of the popup on opening, I don't know how easy it is to implement it without overlaying. I found that jQuery based libraries usually use a function .closest

to do this, but I can't seem to find an alternative in a simple Javascript way.

+3


source to share


1 answer


You don't really need a method closest

for your task. To be able to close the popup by clicking anywhere outside of it, you must bind a handler for the click event on the element body

(or document

) and simply close the popup if that event is detected there.

It will work because the click event raises bubbles in the DOM tree, eventually to the top element for example body

.

Then you make sure you prevent the event from propagating when the event is initialized inside the popup itself, because you are not clicking the event to get to the body (where, if handled, the popup will be closed). To do this, you bind another click event in the container popup

, and when that happens, you prevent it from propagating further:



e.stopPropagation();

      

So when you interact with the popup and its contents, clicking inside while doing something, click events that never reach the body, so the popups never close. But after you click outside of the popup, the bubble click event will be handled by the handler body

and close the popup.

+1


source







All Articles