Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I would not use event.stopPropagation() since it causes exactly the kind of problems you see in solution A. If possible, I would also resort to blur and focus events. When your dropdown is attached to an input, you can close it when the input loses the focus. </p> <p>However, handling click events on the document is not so bad either, so if you want to avoid handling the same click event several times, just unbind it from the document when it is not needed anymore. In addition to the expression being evaluated when clicking outside the dropdown, the directive needs to know whether it is active or not:</p> <pre><code>app.directive('clickAnywhereButHere', ['$document', function ($document) { return { link: function postLink(scope, element, attrs) { var onClick = function (event) { var isChild = $(element).has(event.target).length &gt; 0; var isSelf = element[0] == event.target; var isInside = isChild || isSelf; if (!isInside) { scope.$apply(attrs.clickAnywhereButHere) } } scope.$watch(attrs.isActive, function(newValue, oldValue) { if (newValue !== oldValue &amp;&amp; newValue == true) { $document.bind('click', onClick); } else if (newValue !== oldValue &amp;&amp; newValue == false) { $document.unbind('click', onClick); } }); } }; }]); </code></pre> <p>When using the directive, just provide another expression like this:</p> <pre><code>&lt;your-dropdown click-anywhere-but-here="close()" is-active="isDropdownOpen()"&gt;&lt;/your-dropdown&gt; </code></pre> <p>I have not tested your onClick function. I assume it works as expected. Hope this helps.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload