Scroll to top after route has changed (nested divs)


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:

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

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.


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.


<!-- 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>


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

Answered By – Fidel90

Answer Checked By – Pedro (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.