AngularJS and getting window scroll position in controller AngularJS and getting window scroll position in controller angularjs angularjs

AngularJS and getting window scroll position in controller


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


Inject the $window service into your controller, which is simply a wrapper around the browser window object, and you have the $window.scrollX and $window.scrollY properties.

If you want to respond to changes in scroll, put a watch on them:

$scope.$watch(function () {    return $window.scrollY;}, function (scrollY) {    /* logic */});


The accepted answer lacks teardown code:

ERRONEOUS (lacks teardown)

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

To avoid memory leaks and other undesired behavior, the code needs to do proper teardown when the $scope is destroyed.

$document.on('scroll', scrollHandler);$scope.$on("$destroy", function() {    $document.off('scroll', scrollHandler);});function scrollHandler(ev) {    // 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;    });}