angularjs - 如何在路线更改时重置滚动位置?

标签 angularjs routes

我在 Angular JS 上度过了最初的几个小时,并尝试用它编写 SPA。但是,在更改路线时,滚动位置在更改路线后仍保持在当前位置。这意味着,如果有人读完第二页上的一半文本,则在切换到第二页后,此人将在第二页时最终位于页面中间。 (假设页面同样长。)

当我寻找解决方案时,我只发现人们要求相反,即他们不想在更改页面后更改滚动位置。然而,我什至未能重现这一点。我想知道 Angular JS 的开发是否领先于这,并且我查阅的资料已经过时了。

我创建了一个最小版本来演示我的问题(只需添加两个文件 sample1.htmlsample2.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', {
                    controller: 'noOp',
                    templateUrl: 'sample2.html'
                })
                .otherwise({redirectTo: '/'});
    });
    myApp.controller('noOp', function ($scope) { });
</script>
</body>
</html>

最佳答案

根据 ngView documentation :

autoscroll(optional) string:

Whether ngView should call $anchorScroll to scroll the viewport after the view is updated.

因此,您所要做的就是更改 ng-view 调用以打开自动滚动,如下所示:

<div ng-view autoscroll></div>

关于angularjs - 如何在路线更改时重置滚动位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22779753/

相关文章:

javascript - ngBlur 上的 Angular setPristine

javascript - 如何在 Angular 中的两个 div 中显示数组的元素?

javascript - Angular 模块名称中的点是什么意思

php - 在路由中使用资源时在 Controller 中使用自定义函数 - Laravel

ruby-on-rails - Ruby on Rails——静态页面的独立 Controller 方法

kubernetes - OpenShift edge TLS 终止路由不起作用。 CWWKO0801E : Unable to initialize SSL connection

php - Laravel - 删除一行(表)

php - Route() 不能与 Route::enableFilters() 一起使用

javascript - Angular源码中的正则表达式

javascript - 使用用户输入对 JavaScript 中的对象数组进行排序