你们中有人知道如何在 AngularJS 中很好地处理 anchor 散列链接吗?
我有一个简单的常见问题页面的以下标记
<a href="#faq-1">Question 1</a>
<a href="#faq-2">Question 2</a>
<a href="#faq-3">Question 3</a>
<h3 id="faq-1">Question 1</h3>
<h3 id="faq-2">Question 2</h3>
<h3 id="fa1-3">Question 3</h3>
当单击上述任何链接时,AngularJS 会拦截并将我路由到一个完全不同的页面(在我的情况下,是 404 页面,因为没有与链接匹配的路由。)
我的第一个想法是创建一个匹配“/faq/:chapter”的路由,并在相应的 Controller 中检查匹配元素后的$routeParams.chapter
,然后使用jQuery 向下滚动到它。
但后来 AngularJS 又惹恼了我,而且还是滚动到了页面顶部。
那么,这里有人过去做过类似的事情并且知道一个好的解决方案吗?
编辑:切换到 html5Mode 应该可以解决我的问题,但我们还是必须支持 IE8+,所以我担心这不是一个被接受的解决方案:/
最佳答案
您正在寻找 $anchorScroll()
.
Here's the (crappy) documentation.
基本上你只需注入(inject)它并在你的 Controller 中调用它,它就会滚动到任何具有 $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
编辑:将其与路由一起使用
像往常一样设置你的 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
甚至更简单:
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>
关于javascript - 如何在 AngularJS 中处理 anchor 散列链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14712223/