你们中有谁知道如何很好地处理AngularJS中的锚散列链接吗?

对于一个简单的FAQ页面,我有以下标记

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

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

但是AngularJS又在我身上大便了,还是滚动到页面顶部.

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

编辑:切换到html5模式应该可以解决我的问题,但我们无论如何都要支持IE8+,所以我担心这不是一个被接受的解决方案:/

推荐答案

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>

Javascript相关问答推荐

在nodejs中使用快速路由的API路径

JavaScript替换子 node 导致它们更改为[对象HTMLTable SectionElement]

setFinder关闭模式并重定向到url

如何从JavaScript中的公共方法调用私有方法?

使用useParams路由失败

使用json文件字符串来enum显示类型字符串无法按照计算的enum成员值的要求分配给类型号

类型脚本中只有字符串或数字键而不是符号键的对象

调用removeEvents不起作用

用于编辑CSS样式的Java脚本

使用ThreeJ渲染的形状具有抖动/模糊的边缘

单个HTML中的多个HTML文件

如何在使用rhandsontable生成表时扩展数字输入验证?

在Matter.js中添加从点A到另一个约束的约束

从Nextjs中的 Select 项收集值,但当单击以处理时,未发生任何情况

400 bad request error posting through node-fetch

如何防止ionic 输入中的特殊字符.?

使用类型:assets资源 /资源&时,webpack的配置对象&无效

无法重定向到Next.js中的动态URL

如何在AG-Grid文本字段中创建占位符

如果对象中的字段等于某个值,则从数组列表中删除对象