44

我正在尝试使用复选框和过滤器选项创建一个多选下拉列表。我试图通过点击外部来隐藏列表,但无法弄清楚如何。感谢你的帮助。

http://plnkr.co/edit/tw0hLz68O8ueWj7uZ78c

4

9 回答 9

72

请注意,您的解决方案(问题中提供的 Plunker)在打开第二个弹出窗口(在具有多个选择的页面上)时不会关闭其他框的弹出窗口。

通过单击一个框打开一个新的弹出窗口,单击事件将始终停止。该事件永远不会到达任何其他打开的弹出窗口(关闭它们)。

我通过删除该event.stopPropagation();行并匹配弹出窗口的所有子元素来解决这个问题。

仅当事件元素与弹出窗口的任何子元素都不匹配时,弹出窗口才会关闭。

我将指令代码更改为以下内容:

select.html(指令代码)

link: function(scope, element, attr){

    scope.isPopupVisible = false;

    scope.toggleSelect = function(){
        scope.isPopupVisible = !scope.isPopupVisible;
    }

    $(document).bind('click', function(event){
        var isClickedElementChildOfPopup = element
            .find(event.target)
            .length > 0;

        if (isClickedElementChildOfPopup)
            return;

        scope.$apply(function(){
            scope.isPopupVisible = false;
        });
    });
}

我分叉了你的 plunker 并应用了更改:

Plunker:在外部点击时隐藏弹出 div

截屏:

Plunker 截图

于 2013-06-27T11:52:27.673 回答
53

这是一篇旧帖子,但如果这对这里的任何人有帮助,这里是一个点击外部的工作示例,它不依赖于任何东西,但有角度。

module('clickOutside', []).directive('clickOutside', function ($document) {

        return {
           restrict: 'A',
           scope: {
               clickOutside: '&'
           },
           link: function (scope, el, attr) {

               $document.on('click', function (e) {
                   if (el !== e.target && !el[0].contains(e.target)) {
                        scope.$apply(function () {
                            scope.$eval(scope.clickOutside);
                        });
                    }
               });
           }
        }

    });
于 2015-04-15T22:37:29.583 回答
8

好的,我不得不调用 $apply() 因为事件发生在角度世界之外(根据文档)。

    element.bind('click', function(event) {
    event.stopPropagation();      
    });

    $document.bind('click', function(){
    scope.isVisible = false;
    scope.$apply();
    });
于 2013-01-29T14:25:38.023 回答
7

我通过监听全局点击事件来实现这一点,如下所示:

.directive('globalEvents', ['News', function(News) {
    // Used for global events
    return function(scope, element) {
        // Listens for a mouse click
        // Need to close drop down menus
        element.bind('click', function(e) {
            News.setClick(e.target);
        });
    }
}])

然后通过新闻服务广播事件本身

angular.factory('News', ['$rootScope', function($rootScope) {
    var news = {};
    news.setClick = function( target ) {
        this.clickTarget = target;
        $rootScope.$broadcast('click');
    };
}]);

然后,您可以在任何需要的地方收听广播。这是一个示例指令:

.directive('dropdown', ['News', function(News) {
  // Drop down menu für the logo button
  return {
    restrict: 'E',
    scope: {},
    link: function(scope, element) {
      var opened = true;
      // Toggles the visibility of the drop down menu
      scope.toggle = function() {
        element.removeClass(opened ? 'closed' : 'opened');
        element.addClass(opened ? 'opened' : 'closed');
      };
      // Listens for the global click event broad-casted by the News service
      scope.$on('click', function() {
        if (element.find(News.clickTarget.tagName)[0] !== News.clickTarget) {
          scope.toggle(false);
        }
      });
      // Init
      scope.toggle();
    }
  }
}])

我希望它有帮助!

于 2013-01-29T08:07:47.007 回答
4

我对提供的答案并不完全满意,所以我自己做了。改进:

  • 范围的更多防御性更新。将检查申请/摘要是否已经在进行中
  • 当用户按下退出键时,div 也会关闭
  • 当 div 关闭时,窗口事件未绑定(防止泄漏)
  • 范围被销毁时,窗口事件未绑定(防止泄漏)

    功能链接(范围,$元素,属性,$窗口){

    var el = $element[0],
        $$window = angular.element($window);
    
    function onClick(event) {
        console.log('window clicked');
    
        // might need to polyfill node.contains
        if (el.contains(event.target)) {
            console.log('click inside element');
            return;
    
        }
    
        scope.isActive = !scope.isActive;
        if (!scope.$$phase) {
            scope.$apply();
        }
    }
    
    function onKeyUp(event) {
    
        if (event.keyCode !== 27) {
            return;
        }
    
        console.log('escape pressed');
    
        scope.isActive = false;
        if (!scope.$$phase) {
            scope.$apply();
        }
    }
    
    function bindCloseHandler() {
        console.log('binding window click event');
        $$window.on('click', onClick);
        $$window.on('keyup', onKeyUp);
    }
    
    function unbindCloseHandler() {
        console.log('unbinding window click event');
        $$window.off('click', onClick);
        $$window.off('keyup', onKeyUp);
    }
    
    scope.$watch('isActive', function(newValue, oldValue) {
        if (newValue) {
            bindCloseHandler();
        } else {
            unbindCloseHandler();
        }
    });
    
    // prevent leaks - destroy handlers when scope is destroyed
    scope.$on('$destroy', function() {
        unbindCloseHandler();
    });
    

    }

$window直接进入链接功能。但是,您无需完全执行此操作即可获得$window.

function directive($window) {
    return {
        restrict: 'AE',
        link: function(scope, $element, attributes) {
            link.call(null, scope, $element, attributes, $window);
        }
    };
}
于 2014-11-13T22:24:56.743 回答
4

有一个很酷的指令叫做angular-click-outside. 你可以在你的项目中使用它。使用起来超级简单:

https://github.com/IamAdamJowett/angular-click-outside

于 2015-11-06T10:50:29.890 回答
3

Danny F 发布的答案很棒而且几乎完整,但是 Thịnh 的评论是正确的,所以这是我修改后的指令,用于删除指令的 $destroy 事件的侦听器:

const ClickModule = angular
.module('clickOutside', [])
.directive('clickOutside', ['$document', function ($document) {
    return {
        restrict: 'A',
        scope: {
            clickOutside: '&'
        },
        link: function (scope, el, attr) {
            const handler = function (e) {
                if (el !== e.target && !el[0].contains(e.target)) {
                    scope.$apply(function () {
                        console.log("hiiii");
                        //  whatever expression you assign to the click-outside attribute gets executed here
                        //  good for closing dropdowns etc
                        scope.$eval(scope.clickOutside);
                    });
                }
            }

            $document.on('click', handler);

            scope.$on('$destroy', function() {
                $document.off('click', handler);
            });
        }
    }
}]);

如果您在处理程序方法中放置一个日志,当元素从 DOM 中删除时,您仍然会看到它触发。添加我的小改动就足以将其删除。不是想抢走任何人的风头,但这是对优雅解决方案的修复。

于 2018-11-24T01:59:52.410 回答
0

使用angular-click-out

安装:

bower install angular-click-outside --save
npm install @iamadamjowett/angular-click-outside
yarn add @iamadamjowett/angular-click-outside

用法:

angular.module('myApp', ['angular-click-outside'])

//in your html
<div class="menu" click-outside="closeThis">
...
</div>

//And then in your controller
$scope.closeThis = function () {
    console.log('closing');
}
于 2018-04-27T02:02:15.083 回答
0

我在https://github.com/IamAdamJowett/angular-click-outside中发现了一些实现问题

例如,如果单击的元素从 DOM 中删除,则上面的指令将触发逻辑。这对我不起作用,因为我在模态中有一些逻辑,点击后,用 ng-if 删除了元素。

我重写了他的实现。未经实战测试,但似乎效果更好(至少在我的情况下)

angular
  .module('sbs.directives')
  .directive('clickOutside', ['$document', '$parse', '$timeout', clickOutside]);

const MAX_RECURSIONS = 400;

function clickOutside($document, $parse, $timeout) {
  return {
    restrict: 'A',
    link: function ($scope, elem, attr) {
      // postpone linking to next digest to allow for unique id generation
      $timeout(() => {
        function runLogicIfClickedElementIsOutside(e) {
          // check if our element already hidden and abort if so
          if (angular.element(elem).hasClass('ng-hide')) {
            return;
          }

          // if there is no click target, no point going on
          if (!e || !e.target) {
            return;
          }

          let clickedElementIsOutsideDirectiveRoot = false;
          let hasParent = true;
          let recursions = 0;

          let compareNode = elem[0].parentNode;
          while (
            !clickedElementIsOutsideDirectiveRoot &&
            hasParent &&
            recursions < MAX_RECURSIONS
          ) {
            if (e.target === compareNode) {
              clickedElementIsOutsideDirectiveRoot = true;
            }

            compareNode = compareNode.parentNode;
            hasParent = Boolean(compareNode);
            recursions++; // just in case to avoid eternal loop
          }

          if (clickedElementIsOutsideDirectiveRoot) {
            $timeout(function () {
              const fn = $parse(attr['clickOutside']);
              fn($scope, { event: e });
            });
          }
        }

        // if the devices has a touchscreen, listen for this event
        if (_hasTouch()) {
          $document.on('touchstart', function () {
            setTimeout(runLogicIfClickedElementIsOutside);
          });
        }

        // still listen for the click event even if there is touch to cater for touchscreen laptops
        $document.on('click', runLogicIfClickedElementIsOutside);

        // when the scope is destroyed, clean up the documents event handlers as we don't want it hanging around
        $scope.$on('$destroy', function () {
          if (_hasTouch()) {
            $document.off('touchstart', runLogicIfClickedElementIsOutside);
          }

          $document.off('click', runLogicIfClickedElementIsOutside);
        });
      });
    },
  };
}

function _hasTouch() {
  // works on most browsers, IE10/11 and Surface
  return 'ontouchstart' in window || navigator.maxTouchPoints;
}
于 2020-10-27T19:33:28.050 回答