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

前端 未结 4 545
挽巷
挽巷 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:41

    The drawer is not closing because the click event occurs outside the digest cycle and Angular doesn't know that $scope.open has changed. To fix it you can call $scope.$apply() after $scope.open is set to false, this will trigger the digest cycle.

    $scope.toggleSearch = function () {
        $scope.open = !$scope.open;
        if ($scope.open) {
            $scope.$window.onclick = function (event) {
                closeSearchWhenClickingElsewhere(event, $scope.toggleSearch);
            };
        } else {
            $scope.open = false;
            $scope.$window.onclick = null;
            $scope.$apply(); //--> trigger digest cycle and make angular aware. 
        }
    };
    

    Here is your Fiddle.

    I was also trying to create a directive for the search drawer, if it helps (it needs some fixes :)). Here is a JSBin.

提交回复
热议问题