有人知道如何在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页,因为没有路由匹配这些链接)。

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

但是AngularJS又把我搞砸了,反正就是滚动到页面顶部。

有人在过去做过类似的事情并且知道一个好的解决方法吗?

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


当前回答

$anchorScroll可以解决这个问题,但在Angular的最新版本中,有更好的方法来使用它。

现在,$anchorScroll接受散列作为可选参数,因此您不必更改$location。完全是散列。(文档)

这是最好的解决方案,因为它完全不影响路线。我不能得到任何其他解决方案的工作,因为我使用ngRoute和路由将重新加载,只要我设置$location.hash(id),之前$anchorScroll可以做它的魔法。

下面是如何使用它…首先,在指令或控制器中:

$scope.scrollTo = function (id) {
  $anchorScroll(id);  
}

然后在视图中:

<a href="" ng-click="scrollTo(id)">Text</a>

同样,如果你需要考虑一个固定的导航栏(或其他UI),你可以像这样设置$anchorScroll的偏移量(在主模块的run函数中):

.run(function ($anchorScroll) {
   //this will make anchorScroll scroll to the div minus 50px
   $anchorScroll.yOffset = 50;
});

其他回答

我使用的是AngularJS 1.3.15,看起来我不需要做任何特别的事情。

https://code.angularjs.org/1.3.15/docs/api/ng/provider/ anchorScrollProvider美元

所以,以下工作为我在我的html:

<ul>
  <li ng-repeat="page in pages"><a ng-href="#{{'id-'+id}}">{{id}}</a>
  </li>
</ul>
<div ng-attr-id="{{'id-'+id}}" </div>

我根本不需要对控制器或JavaScript做任何更改。

我使用ng-route的解决方案是这个简单的指令:

   app.directive('scrollto',
       function ($anchorScroll,$location) {
            return {
                link: function (scope, element, attrs) {
                    element.click(function (e) {
                        e.preventDefault();
                        $location.hash(attrs["scrollto"]);
                        $anchorScroll();
                    });
                }
            };
    })

html看起来是这样的:

<a href="" scrollTo="yourid">link</a>

有时在angularjs应用哈希导航不工作和bootstrap jquery javascript库大量使用这种类型的导航,使其工作添加target="_self"到锚标签。 例如:<a data-toggle="tab" href="#id_of_div_to_navigate" target="_self">

见https://code.angularjs.org/1.4.10/docs/api/ngRoute/provider/ routeProvider美元

[reloadOnSearch=true] - {boolean=} -仅当$location.search()或$location.hash()发生变化时重新加载路由。

对我来说,把这个设置为false就可以了。

你可以尝试使用anchorScroll。

例子

所以控制器会是:

app.controller('MainCtrl', function($scope, $location, $anchorScroll, $routeParams) {
  $scope.scrollTo = function(id) {
     $location.hash(id);
     $anchorScroll();
  }
});

和视图:

<a href="" ng-click="scrollTo('foo')">Scroll to #foo</a>

...锚的id也没有秘密:

<div id="foo">
  This is #foo
</div>