Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
21
rated 0 times [  22] [ 1]  / answers: 1 / hits: 41668  / 10 Years ago, tue, october 14, 2014, 12:00:00

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?


More From » angularjs

 Answers
42

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;
})
});

[#69122] Monday, October 13, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaylea

Total Points: 459
Total Questions: 97
Total Answers: 106

Location: Denmark
Member since Wed, Aug 26, 2020
4 Years ago
;