I need to hide a div on click of outside it. So, I have created a directive which handles it(check if the target element is a child. If yes, it will not hide the div or else it hides the div). It is failing(making the div to hide), when we select some option from the typeahead drop down. Any help?
http://plnkr.co/edit/hP740WSct8BuZLm8K1K9?p=preview
Directive:
app.directive("outsideClick", ['$document', '$parse', function($document, $parse) {
return {
link: function($scope, $element, $attributes) {
var scopeExpression = $attributes.outsideClick,
onDocumentClick = function(event) {
var parent = event.target;
while (parent && parent !== $element[0]) {
parent = parent.parentNode;
}
if (!parent) {
$scope.$apply(scopeExpression);
}
}
$document.on("click", onDocumentClick);
$element.on('$destroy', function() {
$document.off("click", onDocumentClick);
});
}
}
}]);
HTML:
<div ng-show="status" outside-click="hideDiv();">
<h3>Div to be made hidden</h3>
<p>Selected: {{address.selected.formatted_address}}</p>
<ui-select ng-model="address.selected" theme="bootstrap" ng-disabled="disabled" reset-search-input="false" style="width: 300px;">
<ui-select-match placeholder="Enter an address...">{{$select.selected.formatted_address}}</ui-select-match>
<ui-select-choices repeat="address in addresses track by $index" refresh="refreshAddresses($select.search)" refresh-delay="0">
<div ng-bind-html="address.formatted_address | highlight: $select.search"></div>
</ui-select-choices>
</ui-select>
</div>
With a bit of flags, it's easy to achieve. See plunker.
Basically you put a flag when clicking on the select tag. In the document click event you check if the flag exists. If it exists you return without hiding. Then you reset the flag.
The important part:
onDocumentClick = function(event) {
// check for flag
if(!$scope.closeFlag) {
$scope.closeFlag = true;
return;
}
// code to hide the div
}