我怎样才能在浏览器窗口的任意位置单击时设置一个变量? [英] How can I set a variable when clicking anywhere in the browser window?

查看:122
本文介绍了我怎样才能在浏览器窗口的任意位置单击时设置一个变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由控制NG-节目我的网站上下拉菜单。当用户点击一个按钮,他们看到的下拉列表。当他们再次点击,下拉是隐藏的:

I have a dropdown menu on my site that is controlled by ng-show. When the user clicks on a button they see the dropdown. When they click again, the dropdown is hidden:

<div class="button" ng-click="show = !show">Click Me</div>
<div ng-show="show" ng-init="show = false">
    <div>You can see me now!</div>
</div>

这工作正常。但是,我要的是显示如果用户点击任何地方,是不是带班的按钮的DIV窗口设置为false。我怎样才能做到这一点?

This works fine. But, what I want is for show to be set to false if the user clicks anywhere in the window that is not the div with class "button". How can I achieve this?

推荐答案

HTML

<div customDropdown>
  <h4>Click here to see dropdown</h4>
  <ul ng-show="dropdownVisible">
    <li ng-click="doSomething()">Item #1</li>
    <li ng-click="doSomething()">Item #2</li>
    <li ng-click="doSomething()">Item #3</li>
  </ul>
</div>

简单的指令:

app.directive('customDropdown', ['$document', function($document) {
  return {
    restrict: 'A',
    link: function(scope, el) {

      // Switch dropdown visibility by clicking on 'target' element
      el.on('click', function(event) {
        event.preventDefault();
        scope.dropdownVisible = !scope.dropdownVisible;
      });

      // Hide dropdown if clicked somewhere 'outside'
      $document.on('click', function(event) {
        scope.dropdownVisible = false;
        return $document.off('click', event);
      });

    }
  };
}]);

这篇关于我怎样才能在浏览器窗口的任意位置单击时设置一个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆