Scroll to top of page if stuck at middle in Angular

Posted By : Gaurav Arora | 28-Jun-2016



Hi, In this blog I’m going to use angular’s autoscroll=”true”, As I had faced the same issue like on click of anchor the new page starts from middle instead of top and my issue is resolved after using autoscroll=”true” in ng-view and with the help of a piece of code. Usually we don’t need these kind of things but when we stucked somewhere we’ll have to use it.

 

The first thing that we have to do is to include autoscroll true in our ng-view like this.


 
 

 

And after that we will include some code in our app.js file in .run part that will help us to overcome the situation.

yourApp.run(function($rootScope, $window) {

  $rootScope.$on('$routeChangeSuccess', function () {

    var interval = setInterval(function(){
      if (document.readyState == 'complete') {
        $window.scrollTo(0, 0);
        clearInterval(interval);
      }
    }, 200);

  });
});
 

 

In this way by including Angular's autoscroll true, you can stop your page to start from middle whenever a new page is clicked.

 

THANKS

About Author

Author Image
Gaurav Arora

Gaurav is an experienced UI developer with experience and capabilities to build compelling UI's for Web and Mobile Applications.

Request for Proposal

Name is required

Comment is required

Sending message..