javascript - Angularjs $anchorScroll 在 ng-view 中不工作

标签 javascript angularjs

我的脚本基于http://plnkr.co/edit/De6bBrkHpojgAbEvHszu 但是我与 ID anchor 的所有链接都在 View 中,每次单击它们都不会将我带到元素,它只是重新加载 View 。 有什么想法吗?

我正在使用的脚本

/*Intercept onpage anchor hash usage: <a href="#/test?scrollTo=foo">Test/Foo</a> */
Site.run(function($rootScope, $location, $anchorScroll, $routeParams) {
  $rootScope.$on('$routeChangeSuccess', function(newRoute, oldRoute) {
    $location.hash($routeParams.scrollTo);
    $anchorScroll();  
  });
})

我的一个链接

<a href="#/article/10?scrollTo=test" target="">Test</a>

我要导航到的元素

<h3 id="test">Test</h3>

最佳答案

希望我正确理解了您的问题。

看来您想链接到文章的特定部分,使用 AngularJS $anchorScroll 来完成。

我在编辑此处发布的任何 Plunkers 时遇到了麻烦。看来他们有缓存问题。 所以我为它造了一支笔:http://cdpn.io/kBqmj

不幸的是,那里不能有多个 HTML 文件,所以我对部分模板进行了硬编码,但它应该与外部文件具有相同的效果。

我将代码分成两个 Controller ,以便于调试。

主页 View 有两个链接指向同一篇文章的不同部分:

<ol>
  <li><a href=\"#/article/1?scrollTo=InterestingStuff\" target=''>Article 1: Interesting stuff</a></li>
  <li><a href=\"#/article/1?scrollTo=ImportantStuff\" target=''>Article 1: Don't miss it stuff</a></li>
</ol>

然后 文章 View 基本上有一些内容和两个元素,它们的 id 和以前一样:

<p>A lot of introduction, followed by something else</p>
<br> 
... 
<br>
<h1 id='InterestingStuff'>Interesting stuff in the middle</h1>
<br> 
... 
<br>
<h1 id='ImportantStuff'>Important stuff at the end</h1>

我不能确切地说出它不适合您的原因,所以请查看我的代码。我希望它至少可以作为您的解决方案的起点。

关于javascript - Angularjs $anchorScroll 在 ng-view 中不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16363932/

相关文章:

javascript - 使用 Angular 服务/工厂的 Setter 和 getter

angularjs - 在这种情况下我应该使用隔离范围吗?

angularjs - Laravel 如何忽略除某些前缀之外的所有内容?

javascript - 带有嵌套 Promise 的函数式编程

javascript - Div 无法使用 angularjs 正确显示

javascript - 无法在javascript中删除带有 "replace"的逗号

javascript - JQuery新手: calling Javascript function from inside JQuery validate

javascript - 页面加载后使用 javascript 更新 TailwindCSS 类

javascript - 在 JSON.parse 函数中传递外部变量

javascript - 为什么 ngRepeat 没有按预期生成有序列表?