Changing route doesn't scroll to top in the new page

后端 未结 18 2046
北恋
北恋 2020-11-29 15:11

I've found some undesired, at least for me, behaviour when the route changes. In the step 11 of the tutorial http://angular.github.io/angular-phonecat/step-11/app/#/phon

18条回答
  •  一向
    一向 (楼主)
    2020-11-29 15:25

    I have finally gotten what I needed.

    I needed to scroll to the top, but wanted some transitions not to

    You can control this on a route-by-route level.
    I'm combining the above solution by @wkonkel and adding a simple noScroll: true parameter to some route declarations. Then I'm catching that in the transition.

    All in all: This floats to the top of the page on new transitions, it doesn't float to the top on Forward / Back transitions, and it allows you to override this behavior if necessary.

    The code: (previous solution plus an extra noScroll option)

      // hack to scroll to top when navigating to new URLS but not back/forward
      let wrap = function(method) {
        let orig = $window.window.history[method];
        $window.window.history[method] = function() {
          let retval = orig.apply(this, Array.prototype.slice.call(arguments));
          if($state.current && $state.current.noScroll) {
            return retval;
          }
          $anchorScroll();
          return retval;
        };
      };
      wrap('pushState');
      wrap('replaceState');
    

    Put that in your app.run block and inject $state... myApp.run(function($state){...})

    Then, If you don't want to scroll to the top of the page, create a route like this:

    .state('someState', {
      parent: 'someParent',
      url: 'someUrl',
      noScroll : true // Notice this parameter here!
    })
    

提交回复
热议问题