我花了我的前几个小时与Angular JS,我正试图写一个SPA。然而,在更改路线时,滚动位置在更改路线后保持在其当前位置。这意味着如果有人通过第二页的一半阅读文本,那么在更改为第二页之后,这个人将在页面中间最后出现。 (鉴于页面同样长。)
当我寻找解决方案时,我只会发现人们要求相反,即他们不想在更改页面时更改滚动位置。但是,即使如此,我也没有再现。我不知道Angular JS的发展是否超前了,我所咨询的消息来源已经过时了。
我创建了一个演示我的问题的最小版本(只需添加两个文件sample1.html和sample2.html随机内容使其工作。):
- <!DOCTYPE html>
- <html>
- <head lang="en"><title>SPA sample</title></head>
- <body data-ng-app="myApp">
- <div style="position: fixed;">
- <a href="#/">Main</a>
- <a href="#/other">Tutorial</a>
- </div>
- <div data-ng-view=""></div>
- <script src="http://code.angularjs.org/1.2.9/angular.min.js"></script>
- <script src="http://code.angularjs.org/1.2.9/angular-route.min.js"></script>
- <script>
- var myApp = angular.module('myApp',['ngRoute']);
- myApp.config(function ($routeProvider) {
- $routeProvider
- .when('/',{
- controller: 'noOp',templateUrl: 'sample1.html'
- })
- .when('/other',templateUrl: 'sample2.html'
- })
- .otherwise({redirectTo: '/'});
- });
- myApp.controller('noOp',function ($scope) { });
- </script>
- </body>
- </html>
根据ngView文档:
autoscroll(optional) string:
Whether ngView should call $anchorScroll to scroll the viewport after
the view is updated.
所以你所要做的就是改变你的ng视图来打开自动滚屏:
- <div ng-view autoscroll></div>