Search code examples
angularjsangularjs-scope

ng-if dependent element not disappearing


I've got the following problem:

When clicking a button my searchResults window opens due to 'displayResults' is set on 'true'. But when clicking on the close button it's not closed even if $scope.displayResults is set to false again.

html

<section id="searchResults" data-ng-if="displayResults">
    <h2>Suchergebnisse:</h2>
    <div id="closeMenuS">&#10060;</div>
    <ul data-ng-repeat="x in sItems">
       ....
    </ul>
</section>

AngularJS

         $http({
            method : "POST",
            url : "/searchFor",
            data: {item: sI, dID: searchID}
          }).then(function(response){

            if(response.data.length > 0 || response.data != 'undefined'){

                $("#sidebar").css({pointerEvents: "none"});
                $("#default").css({pointerEvents: "none"});

                $scope.displayResults = true;
                $scope.sItems = [];

                for(let i = 0; i < response.data.length; i++){
                    $scope.sItems[i] = response.data[i];
                }

                window.setTimeout(function(){
                    $("#closeMenuS").click(function(){
                        $scope.displayResults = false;

                        $("#sidebar").css({pointerEvents: "auto"});
                        $("#default").css({pointerEvents: "auto"});
                    });
                }, 30);



            }

         }, function myError(response) {

                $scope.myWelcome = response.statusText;

          });

Solution

  • If you're in a callback in a jQuery listener, you need to explicitly apply the change. Try this:

                    window.setTimeout(function(){
                        $("#closeMenuS").click(function(){
                            $scope.displayResults = false;
                            $scope.$apply();
                            $("#sidebar").css({pointerEvents: "auto"});
                            $("#default").css({pointerEvents: "auto"});
                        });
                    }, 30);