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>
</button>
<tw-search-modes-dialog show="searchModesVisible" hide-fn="toggleSearchModes"
search-settings="searchModesDlg"
ng-click="$event.stopPropagation()">
</tw-search-modes-dialog>
</div>
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) {
$scope.toggleSearchModes();
}
});
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) {
$scope.toggleSearchModes();
}
});
});