You're looking for $anchorScroll()
.
Here's the (crappy) documentation.
And here's the source.
基本上你只需注入它并在你的控制器中调用它,它就会滚动到任何id为$location.hash()
的元素
app.controller('TestCtrl', function($scope, $location, $anchorScroll) {
$scope.scrollTo = function(id) {
$location.hash(id);
$anchorScroll();
}
});
<a ng-click="scrollTo('foo')">Foo</a>
<div id="foo">Here you are</div>
Here is a plunker to demonstrate
EDIT: to use this with routing
像往常一样设置您的Angular 布线,然后只需添加以下代码.
app.run(function($rootScope, $location, $anchorScroll, $routeParams) {
//when the route is changed scroll to the proper element.
$rootScope.$on('$routeChangeSuccess', function(newRoute, oldRoute) {
$location.hash($routeParams.scrollTo);
$anchorScroll();
});
});
您的链接将如下所示:
<a href="#/test?scrollTo=foo">Test/Foo</a>
这是Plunker demonstrating scrolling with routing and $anchorScroll美元
And even simpler:
app.run(function($rootScope, $location, $anchorScroll) {
//when the route is changed scroll to the proper element.
$rootScope.$on('$routeChangeSuccess', function(newRoute, oldRoute) {
if($location.hash()) $anchorScroll();
});
});
您的链接将如下所示:
<a href="#/test#foo">Test/Foo</a>