Trigger event when clicking off element

1

I'm having a problem with an AngularJS 1.6 implementation.

I need to trigger an event by clicking outside a div element for example.

Note: ng-blur only works with form fields.

<li class="dropdown-toggle" ng-controller="SearchCtrl as ctrl">
  <md-input-container class="search-main">
    <label>Pesquisa</label>
    <input  ng-keyup="ctrl.loadSearchResults(search)" ng-model="search.term">
  </md-input-container>
  <div class="search-results" ng-if="ctrl.openModalSearch" ng-include="'views/search.html'"></div>
</li>

I want to fire the event when I click outside the "li".

    
asked by anonymous 10.10.2017 / 02:35

1 answer

0

With pure JavaScript you can use addEventListener in document and test whether the DIV element in question is in the event propagation array.

I have taken the liberty of making your% color visible to facilitate the test, click in and out of the yellow square:

document.addEventListener('click', evt => {
  if (evt.path.indexOf(document.querySelector('div.search-results')) < 0) {
    alert('fora no div!');
  } else {
    alert('dentro do div!');
  }
}, true);
.search-results {
  width: 100px;
  height: 100px;
  margin: 10px 10px;
  background-color: yellow;
}
<li class="dropdown-toggle" ng-controller="SearchCtrl as ctrl">
  <md-input-container class="search-main">
    <label>Pesquisa</label>
    <input  ng-keyup="ctrl.loadSearchResults(search)" ng-model="search.term">
  </md-input-container>
  <div class="search-results" ng-if="ctrl.openModalSearch" ng-include="'views/search.html'"></div>
</li>

JSFiddle: link

    
10.10.2017 / 05:06