本文介绍了如何处理 AngularJS 中的锚点哈希链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你们知道如何在 AngularJS 中很好地处理锚点哈希链接吗?

Do any of you know how to nicely handle anchor hash linking in AngularJS?

我有一个简单的常见问题解答页面的以下标记

I have the following markup for a simple FAQ-page

<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 页面,因为没有与链接匹配的路由.)

When clicking on any of the above links AngularJS intercepts and routes me to a completely different page (in my case, a 404-page as there are no routes matching the links.)

我的第一个想法是创建一个匹配 "/faq/:chapter" 的路由,并在相应的控制器中检查匹配元素之后的 $routeParams.chapter 然后使用jQuery 向下滚动到它.

My first thought was to create a route matching "/faq/:chapter" and in the corresponding controller check $routeParams.chapter after a matching element and then use jQuery to scroll down to it.

但随后 AngularJS 又对我大发雷霆,无论如何都滚动到页面顶部.

But then AngularJS shits on me again and just scrolls to the top of the page anyway.

那么,这里有人过去做过类似的事情并且知道一个好的解决方案吗?

So, anyone here done anything similar in the past and knows a good solution to it?

切换到 html5Mode 应该可以解决我的问题,但无论如何我们都必须支持 IE8+,所以我担心这不是一个可接受的解决方案:/

Switching to html5Mode should solve my problems but we kinda have to support IE8+ anyway so I fear it's not an accepted solution :/

推荐答案

您正在寻找 $anchorScroll().

You're looking for $anchorScroll().

这是(蹩脚的)文档.

这是来源.

基本上,您只需注入它并在您的控制器中调用它,它就会将您滚动到具有在 $location.hash()

Basically you just inject it and call it in your controller, and it will scroll you to any element with the id found in $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>

这是一个演示

与路由一起使用

像往常一样设置角度路由,然后添加以下代码.

Set up your angular routing as usual, then just add the following code.

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 演示使用路由和 $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>

这篇关于如何处理 AngularJS 中的锚点哈希链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 06:16