基本上,您只需注入它并在控制器中调用它,它将把您滚动到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>编辑:与路由一起使用
像往常一样设置您的角度路由,然后只需添加以下代码。
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>
甚至更简单:
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>



