当路线改变时,我发现了一些不受欢迎的行为,至少对我来说是这样。在教程 http://angular.github.io/angular-phonecat/step-11/app/#/phones 的第 11 步中,您可以看到电话列表。如果您滚动到底部并单击最新的一个,您会看到滚动不在顶部,而是在中间。
我也在我的一个应用程序中发现了这个,我想知道如何让它滚动到顶部。我可以手动完成,但我认为应该有其他优雅的方式来做到这一点,我不知道。
那么,当路线改变时,是否有一种优雅的方式滚动到顶部?
问题是您的 ngView 在加载新视图时会保留滚动位置。您可以指示 $anchorScroll
“在视图更新后滚动视口”(docs 有点含糊,但此处的滚动表示滚动到新视图的顶部)。
解决方案是将 autoscroll="true"
添加到您的 ngView 元素中:
<div class="ng-view" autoscroll="true"></div>
只需将此代码运行
$rootScope.$on("$routeChangeSuccess", function (event, currentRoute, previousRoute) {
window.scrollTo(0, 0);
});
$window.scrollTop(0,0)
对我来说比自动滚动效果更好。在我的情况下,我有进入和离开转换的视图。
这段代码对我很有用..我希望它也对你有用..你所要做的就是将 $anchorScroll 注入你的运行块并将监听器函数应用到 rootScope 就像我在下面的例子中所做的那样......
angular.module('myAngularApp')
.run(function($rootScope, Auth, $state, $anchorScroll){
$rootScope.$on("$locationChangeSuccess", function(){
$anchorScroll();
});
下面是 Angularjs 模块的调用顺序:
app.config() app.run() 指令的编译函数(如果在 dom 中找到) app.controller() 指令的链接函数(再次,如果找到)
RUN BLOCK 在注入器创建后执行并用于启动应用程序。这意味着当您重定向到新的路由视图时,运行块中的侦听器会调用
$anchorScroll()
你现在可以看到滚动开始到顶部,新的路由视图:)
在尝试了 ui-view autoscroll=true
、$stateChangeStart
、$locationChangeStart
、$uiViewScrollProvider.useAnchorScroll()
、$provide('$uiViewScroll', ...)
和许多其他组合的一两个小时后,我无法在新页面上滚动到顶部按预期工作。
这最终对我有用。它捕获 pushState 和 replaceState 并且仅在导航到新页面时更新滚动位置(后退/前进按钮保留其滚动位置):
.run(function($anchorScroll, $window) {
// hack to scroll to top when navigating to new URLS but not back/forward
var wrap = function(method) {
var orig = $window.window.history[method];
$window.window.history[method] = function() {
var retval = orig.apply(this, Array.prototype.slice.call(arguments));
$anchorScroll();
return retval;
};
};
wrap('pushState');
wrap('replaceState');
})
$locationProvider.html5Mode(true);
@wkronkel 在不使用 Angular 中的 HTML5 模式时有没有办法做到这一点?由于 html 5 模式处于活动状态,导致页面重新加载引发 404 错误
.run
附加到哪里? app
对象的角度?
run
函数是每个角度模块对象都可用的方法。
这是我(看似)强大、完整且(相当)简洁的解决方案。它使用缩小兼容样式(以及对您的模块的 angular.module(NAME) 访问)。
angular.module('yourModuleName').run(["$rootScope", "$anchorScroll" , function ($rootScope, $anchorScroll) {
$rootScope.$on("$locationChangeSuccess", function() {
$anchorScroll();
});
}]);
PS我发现自动滚动的东西无论设置为true还是false都没有效果。
使用 angularjs UI Router,我正在做的是:
.state('myState', {
url: '/myState',
templateUrl: 'app/views/myState.html',
onEnter: scrollContent
})
和:
var scrollContent = function() {
// Your favorite scroll method here
};
它在任何页面上都不会失败,而且它不是全局的。
onEnter: scrollContent
// Your favorite scroll method here
的地方放了什么?
$('html, body').animate({ scrollTop: -10000 }, 100);
onEnter: scrollContent
时,它仅适用于第一个视图/路线,而不适用于第二个视图/路线。奇怪的。
仅供任何遇到标题中描述的问题的人(就像我一样)也使用 AngularUI Router 插件...
正如在这个 SO question 中询问和回答的那样,当您更改路由时,angular-ui 路由器会跳转到页面底部。
Can't figure out why page loads at bottom? Angular UI-Router autoscroll Issue
但是,正如答案所述,您可以通过在您的 ui-view
上说 autoscroll="false"
来关闭此行为。
例如:
<div ui-view="pagecontent" autoscroll="false"></div>
<div ui-view="sidebar" autoscroll="false"></div>
http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.directive:ui-view
如果您使用 ui-router 您可以使用(运行时)
$rootScope.$on("$stateChangeSuccess", function (event, currentState, previousState) {
$window.scrollTo(0, 0);
});
你可以使用这个 javascript
$anchorScroll()
$anchorScroll()
之前使用 $location.hash('top')
指定位置,默认的前进/后退浏览器按钮将不再起作用;他们不断将您重定向到 URL 中的哈希值
我找到了这个解决方案。如果您转到新视图,该函数将被执行。
var app = angular.module('hoofdModule', ['ngRoute']);
app.controller('indexController', function ($scope, $window) {
$scope.$on('$viewContentLoaded', function () {
$window.scrollTo(0, 0);
});
});
将 autoScroll 设置为 true 对我来说不是诀窍,所以我确实选择了另一种解决方案。我构建了一个服务,该服务会在每次路由更改时挂钩,并使用内置的 $anchorScroll 服务滚动到顶部。为我工作:-)。
服务:
(function() {
"use strict";
angular
.module("mymodule")
.factory("pageSwitch", pageSwitch);
pageSwitch.$inject = ["$rootScope", "$anchorScroll"];
function pageSwitch($rootScope, $anchorScroll) {
var registerListener = _.once(function() {
$rootScope.$on("$locationChangeSuccess", scrollToTop);
});
return {
registerListener: registerListener
};
function scrollToTop() {
$anchorScroll();
}
}
}());
登记:
angular.module("mymodule").run(["pageSwitch", function (pageSwitch) {
pageSwitch.registerListener();
}]);
聚会有点晚了,但我已经尝试了所有可能的方法,但没有一个能正常工作。这是我优雅的解决方案:
我使用一个控制器,它通过 ui-router 管理我的所有页面。它允许我将未经过身份验证或验证的用户重定向到适当的位置。大多数人将他们的中间件放在他们应用程序的配置中,但我需要一些 http 请求,因此全局控制器对我来说效果更好。
我的 index.html 看起来像:
<main ng-controller="InitCtrl">
<nav id="top-nav"></nav>
<div ui-view></div>
</main>
我的 initCtrl.js 看起来像:
angular.module('MyApp').controller('InitCtrl', function($rootScope, $timeout, $anchorScroll) {
$rootScope.$on('$locationChangeStart', function(event, next, current){
// middleware
});
$rootScope.$on("$locationChangeSuccess", function(){
$timeout(function() {
$anchorScroll('top-nav');
});
});
});
我已经尝试了所有可能的选项,这种方法效果最好。
id="top-nav"
放在正确的元素上也很重要。
简单的解决方案,在启用的主路由模块中添加 scrollPositionRestoration
。
像这样:
const routes: Routes = [
{
path: 'registration',
loadChildren: () => RegistrationModule
},
];
@NgModule({
imports: [
RouterModule.forRoot(routes,{scrollPositionRestoration:'enabled'})
],
exports: [
RouterModule
]
})
export class AppRoutingModule { }
上面的所有答案都破坏了预期的浏览器行为。大多数人想要的是,如果它是一个“新”页面,它会滚动到顶部,但如果你通过后退(或前进)按钮返回到上一个位置。
如果你假设 HTML5 模式,这很容易(尽管我相信一些聪明的人可以弄清楚如何使它更优雅!):
// Called when browser back/forward used
window.onpopstate = function() {
$timeout.cancel(doc_scrolling);
};
// Called after ui-router changes state (but sadly before onpopstate)
$scope.$on('$stateChangeSuccess', function() {
doc_scrolling = $timeout( scroll_top, 50 );
// Moves entire browser window to top
scroll_top = function() {
document.body.scrollTop = document.documentElement.scrollTop = 0;
}
它的工作方式是路由器假设它会滚动到顶部,但会延迟一点,让浏览器有机会完成。如果浏览器随后通知我们更改是由于后退/前进导航,它会取消超时,并且滚动永远不会发生。
我使用原始 document
命令滚动,因为我想移动到窗口的整个顶部。如果您只想让 ui-view
滚动,则使用上述技术在您控制 my_var
的位置设置 autoscroll="my_var"
。但是我认为,如果您要以“新”的身份访问该页面,大多数人会想要滚动整个页面。
以上使用 ui-router,但您可以通过将 $routeChangeSuccess
替换为 $stateChangeSuccess
来使用 ng-route。
var routerApp = angular.module('routerApp', ['ui.router']); routerApp.config(function($stateProvider, $urlRouterProvider, $locationProvider) { $urlRouterProvider.otherwise('/home'); $locationProvider.html5Mode(false).hashPrefix(""); $stateProvider // HOME STATES AND NESTED VIEWS ======================================== .state('home', { url: '/home', templateUrl: 'partial-home.html' }) });
.state('web', { url: '/webdev', templateUrl: 'partial-web.html', controller: function($scope) { $scope.clients = ['client1', 'client2', 'client3']; // I put it here } })
我只是在学习这些东西,也许我错过了一些东西 :D
提供的答案都没有解决我的问题。我在视图之间使用动画,并且滚动总是在动画之后发生。我发现在动画之前滚动到顶部的解决方案是以下指令:
yourModule.directive('scrollToTopBeforeAnimation', ['$animate', function ($animate) {
return {
restrict: 'A',
link: function ($scope, element) {
$animate.on('enter', element, function (element, phase) {
if (phase === 'start') {
window.scrollTo(0, 0);
}
})
}
};
}]);
我将它插入到我的视图中,如下所示:
<div scroll-to-top-before-animation>
<div ng-view class="view-animation"></div>
</div>
我终于得到了我需要的东西。
我需要滚动到顶部,但希望一些过渡不要
您可以在逐个路由级别进行控制。
我正在通过@wkonkel 组合上述解决方案,并在一些路由声明中添加一个简单的 noScroll: true
参数。然后我在过渡中抓住了这一点。
总而言之:这会在新转换时浮动到页面顶部,在 Forward
/ Back
转换时不会浮动到顶部,并且它允许您在必要时覆盖此行为。
代码:(以前的解决方案加上一个额外的 noScroll 选项)
// 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');
将其放入您的 app.run
块并注入 $state
... myApp.run(function($state){...})
然后,如果您不想滚动到页面顶部,请创建如下路线:
.state('someState', {
parent: 'someParent',
url: 'someUrl',
noScroll : true // Notice this parameter here!
})
这对我有用,包括自动滚动
<div class="ngView" autoscroll="true" >
<div class="ng-view" autoscroll></div>
并且它的工作原理相同(除非您想使滚动有条件)。$window.scrollTo(0,0)