Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a click binded to $document

Tags:

angularjs

I have a popup that i want to close when clicked anywhere else on screen, I do this by triggering $document.bind('click',function(){...}); inside the open function $scope.open = function(){...}.

I also have another function for close $scope.close = function(){...}

The objective is to remove the bind inside the close function.

I am new to angular and so unfortunately I dont fully understand the answers I've found on this questions. Theoretically, I know I might be able to achieve this with $destroy, but I have no idea how to physically implement it. Can someone please teach me how to do this?

EDIT: I am doing this in controllers & directives.

like image 478
muudless Avatar asked Nov 05 '14 08:11

muudless


People also ask

How do you unbind a click event?

jQuery unbind() Method Use the off() method instead. The unbind() method removes event handlers from selected elements. This method can remove all or selected event handlers, or stop specified functions from running when the event occurs. This method can also unbind event handlers using an event object.

How do I remove all event listeners?

To remove all event listeners from an element: Use the cloneNode() method to clone the element. Replace the original element with the clone. The cloneNode() method copies the node's attributes and their values, but doesn't copy the event listeners.

Which function is used to remove an existing event handler?

The removeEventListener() method removes an event handler from an element.

What is bind and unbind in jQuery?

jQuery bind() function is used to attach an event handler to elements, while the unbind() is used to detached an existing event handler from elements.


2 Answers

When the popup shows, do:

$document.on('click', documentClick);

and in documentClick hide the popover, and do:

$document.off('click', documentClick);

If you encapsulate the popup behavior in a myPopover directive, define these in the link function of the directive. Don't manipulate the DOM in the controller function of the popover directive, and don't do that in a general controller of a page.

like image 134
seldary Avatar answered Nov 15 '22 04:11

seldary


you can unbind event with the method unbind()

$document.unbind('click');

will remove your event handler

refer to angular.element documentation

like image 24
laurent Avatar answered Nov 15 '22 05:11

laurent