Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS and getting window scroll position in controller

I'm having some trouble understanding how to get the scroll position of window within my controller, so I can build logic around it.

From all the questions and answers I've been reading the most accepted answer seems to be to write a directive that calculates the scroll position, stick that directive on an element, and that's it.

However, when you want to do something along the lines of:

if (scrollY > 100 ){
  $scope.showMenu = true;
}

if (scrollY > 500) {
  $scope.showFooter = true;
}

This approach doesn't seem to work, because the calculated position in the directive can't be accessed from the controller. What would be the right 'Angular' way of doing this, which would still allow slightly more complicated logic to be executed from the controller?

like image 973
Squrler Avatar asked Oct 14 '14 16:10

Squrler


People also ask

How do you get the scroll bar position?

How can I get the scrollbar position? To get or set the scroll position of an element, you follow these steps: First, select the element using the selecting methods such as querySelector() . Second, access the scroll position of the element via the scrollLeft and scrollTop properties.


1 Answers

According to @RobKohr comment, here's a optimized approach using .on('scroll') and $scope.$apply to update a scope element on scroll.

$document.on('scroll', function() {
    // do your things like logging the Y-axis
    console.log($window.scrollY);

    // or pass this to the scope
    $scope.$apply(function() {
        $scope.pixelsScrolled = $window.scrollY;
    })
});
like image 60
Zachary Dahan Avatar answered Sep 25 '22 01:09

Zachary Dahan