Search code examples
javascriptangularjsscrolltopdocument-body

Function fired on all controller- angualrjs


I have this

  $window.onscroll = function() { scrollFunction() };

            function scrollFunction() {
                if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
                    document.getElementById("btt").style.display = "block";
                } else {
                    document.getElementById("btt").style.display = "none";
                }
            }

function in one contoller, but the scrollFunction gets fired even after I navigate to another page. how to limit that functionality only to the particualr page(controller).


Solution

  • you need stop listening scroll event when controller destroy

    angular.element($window).on('scroll', scrollFunction);
    
    scope.$on('$destroy', function () {
    
      angular.element($window).off('scroll', scrollFunction);
    });