Our directive features a popup that loads a template with a directive to capture all clicks in the document.
When a click is detected, it sends an event to close the popup and unbinds the event on the $document
.
This directive effectively captures document clicks.
aOS.directive('catchOutsideClick',
[
'$document',
'eventsService',
function CatchOutsideClickDirective($document, eventsService) {
var CatchClick = function CatchClick(scope, element, attrs) {
// Check if parent or its children were clicked
function isDescendant(parent, child) {
var node = child.parentNode;
while (node !== null) {
if (node === parent) {
return true;
}
node = node.parentNode;
}
return false;
}
// Handle outside clicks
var onOutsideClick = function onOutsideClick(event) {
var clickedItem = event.target;
if (!isDescendant(element[0], clickedItem) && element[0] !== clickedItem) {
eventsService.publish('clicked-outside-popup', element[0]);
$document.unbind('click', onOutsideClick);
}
};
// Listen for clicks
$document.bind('click', onOutsideClick);
};
return {
restrict: 'A',
scope: false,
link: CatchClick
};
}
]
);
This is the HTML code responsible for loading the popup:
<div id="header" ng-controller="framework.header">
<div data-ng-include="popupTemplate"></div>
</div>
To simplify things, the controller framework.header
toggles the $scope.popupTemplate
to a specific HTML path:
<div ng-controller="user.profle" catch-outside-click>
<!-- lots of content -->
</div>
While the template inclusion seems to work seamlessly, here's the observed behavior:
- You click a button to toggle the
popupTemplate
, which then loads into the popup div. - The catch-outside-click directive responds correctly, binding a click handler to the document.
- A click inside the popup does not trigger anything due to the directive, but clicking outside the popup closes it by broadcasting an event caught in the header controller.
- Clicking anywhere else on the page does not retrigger the directive, indicating it has been properly unbound.
- However, reopening the popup by clicking the button both binds a new document click event and immediately triggers the clickhandler as well, possibly referencing the initial click handler.
I am unsure whether the first or second click handler is being triggered at this point.
If anyone has any insights on how to troubleshoot this issue or to pinpoint which event handler is active, I would appreciate your input.