javascript – 在AngularStrap的ScrollSpy中正确处理锚点

如何正确使用AngularStrap的ScrollSpy界面链接到当前文档中的锚点?

看一下AngularStrap documentation,我看到当访问链接时,实际上会生成一个双哈希.如:http://mgcrea.github.io/angular-strap/##scrollspy

但是,在自己实现功能时,我没有看到这种行为.在我的情况下,锚标签试图更新位置而不是移动到当前文档中的位置.

我的AngularStrap ScrollSpy位于子页面:my-site.com/#/hig.具有以下定义:

<div class="hig-sidebar hidden-print hidden-sm hidden-xs" role="complementary" data-offset-top="-34" bs-affix bs-scrollspy-list>
  <ul class="nav hig-sidenav">
    <li bs-scrollspy data-target="#overview">
      <a href="#overview">Overview</a>
      <ul class="nav">
        <li bs-scrollspy data-target="#suboverview"><a href="#suboverview">Subsection</a></li>
      </ul>
    </li>
    <li bs-scrollspy data-target="#accessibility"><a href="#accessibility">Accessibility</a></li>
    <li bs-scrollspy data-target="#typography"><a href="#typography">Color and Typography</a></li>
    <li bs-scrollspy data-target="#graphics"><a href="#graphics">Icons and Graphics</a></li>
    <li bs-scrollspy data-target="#navigation"><a href="#navigation">Navigation Design</a></li>
    <li bs-scrollspy data-target="#elements"><a href="#elements">UI Elements</a></li>
    <li bs-scrollspy data-target="#reference"><a href="#reference">Reference</a></li>
  </ul>
  <a href ng-click="gotoTop()">Back to top</a>
</div>

当我滚动文档时,ScrollSpy会正确显示当前部分.但是当我点击链接时,例如“颜色和排版”链接,它会将URL更新为:my-site.com/#typography.

我一直在查看AngularStrap代码,看不到它没有做的事情.如何确保锚链接添加到#/ hig而不是替换它?

最佳答案 是的,正如我在这里解释的那样:

https://github.com/mgcrea/angular-strap/issues/573

在Angularjs中,锚点链接如< a href =“#overview”> Overview< / a>有$routeProvider配置路由时不起作用.
您可以通过用控制器替换锚链接来修复此问题,如下所示:

控制器:

$scope.scrolltoHref = function (id){
        // set the location.hash to the id of
        // the element you wish to scroll to.
        $location.hash(id);
        // call $anchorScroll()
        $anchorScroll();
    };

HTML:

<a href="" ng-click="scrolltoHref('overview')">Overview</a> 
点赞