Document click event does not render deletion of dialog


Since I am new to AngularJS and Javascript… this might be a pretty novice question.
I am trying to create a button that opens a dialog (that displays let’s say search modes), which should close after I press anywhere except this dialog.
This is my code:

In the HTML file:

<div class="form-group dropdown-dialog">
  <button id="searchModesBtn" class="btn btn-sm btn-default pull-left" ng-click="$event.stopPropagation(); toggleSearchModes()"
          title="Open Search Modes"><i class="fa fa-bars"></i>
  <tw-search-modes-dialog show="searchModesVisible" hide-fn="toggleSearchModes"

In the JS file:

$scope.toggleSearchModes = function () {
  if (!$scope.searchModesVisible) {
    $scope.searchModesDlg = {};
  } else {
    delete $scope.searchModesDlg;
  $scope.searchModesVisible = !$scope.searchModesVisible;

$document.bind('click', function(event) {
  if ($scope.searchModesVisible) {

In order to avoid any confusion, the dialog is called tw-search-modes-dialog and is implemented in two separate files (html/js) as a popover element. If
The second part of my JS file handles the clicking event anywhere on the screen in order to close the dialog. Now, everything works great except one thing. I need to click twice outside of the dialog in order for it to close.

After debugging the code, I noticed that when I click anywhere for the first time the event gets triggered successfully, calls the toggleSearchModes function and deletes the dialog, but this deletion does not render on screen (the dialog stays open).

When clicking on the button instead of anywhere on screen, then again the toggleSearchModes function gets called (this time from the ng-click attribute) and does exactly the same thing, i.e. delete the dialog. This time this also shows on screen. The dialog disappears.

What is the difference between calling toggleSearchModes from the button’s ng-click and from a $document.bind('click', function(event)) handler and what can I do in order to render the deletion of the dialog in the second case.


Try changing it so that click event is in a $scope.$apply

$document.bind('click', function(event) {
    $scope.$apply(function () {
         if ($scope.searchModesVisible) {

Answered By – Umer Z

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published