Not sure how to hide a div when clicking OUTSIDE of the div

前端 未结 4 532
挽巷
挽巷 2020-12-23 17:20

This is a follow-up question to this question: AngularJS input with focus kills ng-repeat filter of list

Basically my code is using AngularJS to pop-out a div (a dra

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-23 17:42

    I couldn't find a solution i was 100% happy with, this is what i used:

    {{ email }}

    the span with ng-click is used to open the menu, the div.accountMenu is toggled open or closed

    $scope.accountMenu = false;
    $scope.toggleAccountMenu = function(e){
        if(e) e.stopPropagation();
        $scope.accountMenu = !$scope.accountMenu;
        if ($scope.accountMenu) {
            $window.onclick = function(e) {
                var target = $(e.target);
                if(!target) return;
                if(!target.hasClass('accountMenu') && !target.is($('.accountMenu').children())){
                    $scope.toggleAccountMenu();
                }               
            };
        } else if (!e) {
            $window.onclick = null;
            $scope.$apply();
        }
    }
    

    This uses jQuery for child checking but you can probably do it without if needed.

    I was getting some nasty errors with other peoples version, like trying to call $apply() when its already in a cycle, my version prevents propagation and safe-checks against $apply()

提交回复
热议问题