Scroll to top after route has changed (nested divs)

Issue

I’m using angularJS with ngRoute. When the user scrolls down and then changes the route the new page is scrolled down as well. I have read about using autoscroll="true" with ngView attribute. But my problem is that because of my HTML structure the scrolling container is NOT my ngView. In my case it looks kind of this:

<body>
    <!-- main container allows overflow scrolling and should be scrolled to top -->
    <main>
        <!-- this container has no scrolling -->
        <div ngView><!-- content comes here --></div>
    </main>
</body>

So that’s why an autoscroll="true" on my ngView does nothing as there is nothing to scroll. What should be scrolled is the container above my ngView (main in this case).

How could I do this? I’d prefer as less/easy JS as possible. A HTML solution like the autoscroll property would be nice ofcourse.

Solution

I have figured out a way to do this. I’ve created a directive that will scroll to the top of my container every time the route has been changed. I can listen to this via the $routeChangeSuccess event in $rootScope. The scrollTop() function is part of jQuery which I’m using anyway.

HTML:

<!-- scrollable content container -->
<main id="pageWrap" scroll-top-on-route-change>
    <!-- non-scrollable page content, templates inserted by ngView -->
    <div id="pageContent" ng-view></div>
</main>

JS:

app.directive("scrollTopOnRouteChange", [
    "$rootScope",
    function ($rootScope) {
        return {
            restrict: "A",
            link : function ($scope, $element) {
                $rootScope.$on("$routeChangeSuccess", function () {
                    $element.scrollTop(0);
                });
            }
        };
    }
]);

Answered By – Fidel90

Answer Checked By – Pedro (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.