Angular ui-router scroll to top, not to ui-view

后端 未结 10 1367
情话喂你
情话喂你 2020-12-12 16:00

I\'ve just upgraded to ui-router 0.2.8 from 0.2.0 and I\'ve noticed that when the state changes, the scroll position jumps to the top of te child <

相关标签:
10条回答
  • 2020-12-12 16:47

    when ever the path changes the router broadcasts an event: $stateChangeSuccess i.e. the url has changed so just listen to it and use jquery to scroll to the top of the page

    $rootScope.$on('$stateChangeSuccess',function(){
        $("html, body").animate({ scrollTop: 0 }, 200);
    })
    

    place the above code inside

    yourAppName.run(function(){
    
        //the above code here
     })
    
    0 讨论(0)
  • 2020-12-12 16:51

    Another approach is to decorate the default $uiViewScroll service, effectively overriding the default behaviour.

    app.config(function ($provide) {
      $provide.decorator('$uiViewScroll', function ($delegate) {
        return function (uiViewElement) {
          // var top = uiViewElement.getBoundingClientRect().top;
          // window.scrollTo(0, (top - 30));
          // Or some other custom behaviour...
        }; 
      });
    });
    

    And as Hubrus mentioned, for any <ui-view> you do not wish this to apply for, simply add autoscroll="false". I haven't taken a good look into the actual scrolling implementation, I just figured I'd mention the decorator way (it's alot of fun) as an alternative. I'm sure you can work out the exact scrolling behaviour.

    0 讨论(0)
  • 2020-12-12 16:53

    Since $stateChangeSuccess seems not to be available anymore in current AngularJS (as 1.2.x) I changed Rishul Mattas example to the following which works fine for me:

    app.run(function ($rootScope) {
      $rootScope.$on('$viewContentLoaded',function(){
        jQuery('html, body').animate({ scrollTop: 0 }, 200);
      });
    });
    
    0 讨论(0)
  • 2020-12-12 16:55

    Place on top

    <div id="top">.....
    

    Code to scroll:

    $rootScope.$on('$stateChangeStart', function() {
        $anchorScroll('top');
    });
    
    0 讨论(0)
提交回复
热议问题