javascript - 如何在 AngularJS 中处理 anchor 散列链接

标签 javascript angularjs anchor hashtag

你们中有人知道如何在 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.

And here's the source.

基本上你只需注入(inject)它并在你的 Controller 中调用它,它就会滚动到任何具有 $location.hash()

中的 id 的元素
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/

相关文章:

angularjs - UI Bootstrap 下拉指令导致多目录问题

javascript - 在内部链接上,例如#id 是否有一个事件被触发,我可以附加一个处理程序?

javascript - 全日历重复事件排除

javascript - AngularUI DatePicker - JavaScript - 获取 SQL 日期格式时休息一天

javascript - 使用内联 CSS 在 React 元素中以相反的顺序显示 <li>

javascript - 如何使 Angular 掩码适用于各种信用卡?

html - 当 anchor 标记首先出现在 block 元素中时,ie8 中的奇怪行为

html - 如何创建一个像链接一样的 HTML 按钮?

javascript - 复选框文本不可见

javascript - 来自嵌入指令的 Angular 气泡事件