5

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.

muudless
  • 7,422
  • 7
  • 39
  • 57
  • 2
    Don't manipulate DOM within a controller. You must have come across that in your reading about Angular? Assume that a controller has no clue that DOM exists. – New Dev Nov 05 '14 at 08:03
  • The OP never mentioned a controller. Maybe he/she is using the link function? – seldary Nov 05 '14 at 08:13
  • @NewDev that makes sense but unfortunately I don't know any other way to close a popup. Can you recommend anything? – muudless Nov 05 '14 at 08:18
  • @seldary I am using this in controllers and directives, so its getting pretty messy. – muudless Nov 05 '14 at 08:19
  • @muudless, http://stackoverflow.com/questions/15812203/angularjs-show-popups-the-most-elegant-way – New Dev Nov 05 '14 at 08:23
  • @NewDev Thank you for the resource, I've read that during my research and understands it theoretically, but unfortunately don't know how to implement it – muudless Nov 05 '14 at 08:27

2 Answers2

5

you can unbind event with the method unbind()

$document.unbind('click');

will remove your event handler

refer to angular.element documentation

laurent
  • 2,590
  • 18
  • 26
  • 8
    This will also unbind other handlers, which might break other functionality, defined elsewhere. – seldary Nov 05 '14 at 08:11
5

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.

seldary
  • 6,186
  • 4
  • 40
  • 55
  • Thank you so much, I've moved the elements into a directive and applied your suggestion and it worked like a charm. – muudless Nov 05 '14 at 08:52