9

Tell me please, how can I disable auto-upto top of my page? If I use hash nav:

<a href="#/index">Goto index</a>

my page doest up to top, but if I use AngularJS: Html:

<a ng-href="#/index">Goto index</a>

JS:

$routeProvider.
      when('/index', {
          template:'...',
          controller: 'RouteCtrl'
      })

my page scrolled to top. How can I disable it?

3 Answers 3

23

I find it a bit strange that your plain href doesn't scroll and ng-href scrolls, I thought it was the other way round...

But, to the solution; It's up to the browser to scroll on hash changes, so usually to disable it you need to intercept and preventDefault() the event and then change the location by yourself. When using Angular, you can either define some attribute directive for the <a> element or just define your own a directive.

If you use ng-view, it relies on $anchorScroll service with view updates to simulate the behaviour what the browser would normally do, as Angular already intercepts the event. You can prevent the scroll on view load by providing your own $anchorScroll which does nothing:

angular.module('yourModule', []).value('$anchorScroll', angular.noop);
4
  • the code supplied does the job. FYI using href or ng-href doesn't seem to make any difference. I use href as my links are properly set from the start.
    – Jacob
    Commented Apr 18, 2013 at 17:39
  • @Jawa I am running into similar issue, added the code you suggested with no success. Here is the question with code examples stackoverflow.com/questions/18283979/…
    – anazimok
    Commented Sep 11, 2013 at 3:33
  • This nukes autoscroll on the whole site, not just the one page.
    – Jason
    Commented May 13, 2014 at 17:36
  • I dont like this solution either. Overriding a whole service is a bad idea :/ Commented Jun 6, 2014 at 16:53
3

As indicated in the AngularJS documentation, the proper way to do this is:

angular.module('yourModule',[]).config( ['$anchorScrollProvider', 
    function($anchorScrollProvider) {
        $anchorScrollProvider.disableAutoScrolling();
    }]
);
1
  • To clarify, this doesn't disable all scrolling. It simply turns off $scrollAnchor's watch on $location.hash(). As such, I don't think it applies to this particular case (changing views). If the the issue was not wanting it to scroll when you set $location.hash() then this is the fix. Commented Feb 14, 2014 at 1:12
1

just try

assessmentApp.run(['$anchorScroll', function($anchorScroll) {
    $anchorScroll = angular.noop;
}])
1
  • I'm not sure if this answer solves the specific question above, but it does prevent Angular from scrolling to the top of the page when an $http request completes. Commented Sep 12, 2016 at 18:27

Not the answer you're looking for? Browse other questions tagged or ask your own question.