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?

Paul Kononenko
  • 9,407
  • 4
  • 18
  • 13

3 Answers3

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);
Jawa
  • 2,336
  • 6
  • 34
  • 39
  • 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 Apr 18 '13 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 http://stackoverflow.com/questions/18283979/how-to-disable-anchorscroll-in-angularjs-ng-view – anazimok Sep 11 '13 at 03:33
  • This nukes autoscroll on the whole site, not just the one page. – Jason May 13 '14 at 17:36
  • I dont like this solution either. Overriding a whole service is a bad idea :/ – Anastasios Andronidis Jun 06 '14 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();
    }]
);
Miguel Ping
  • 18,082
  • 23
  • 88
  • 136
Spain Train
  • 5,890
  • 2
  • 23
  • 29
  • 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. – Madeline Trotter Feb 14 '14 at 01:12
1

just try

assessmentApp.run(['$anchorScroll', function($anchorScroll) {
    $anchorScroll = angular.noop;
}])
IHadzera
  • 11
  • 2
  • 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. – Daniel Bonnell Sep 12 '16 at 18:27