当前位置:   article > 正文

如何在AngularJS中处理锚点哈希链接_angularjs $locationprovider

angularjs $locationprovider

本文翻译自:How to handle anchor hash linking in AngularJS

Do any of you know how to nicely handle anchor hash linking in AngularJS ? 你们当中有人知道如何在AngularJS中很好地处理锚点哈希链接吗?

I have the following markup for a simple FAQ-page 我为简单的常见问题解答页面添加了以下标记

  1. <a href="#faq-1">Question 1</a>
  2. <a href="#faq-2">Question 2</a>
  3. <a href="#faq-3">Question 3</a>
  4. <h3 id="faq-1">Question 1</h3>
  5. <h3 id="faq-2">Question 2</h3>
  6. <h3 id="fa1-3">Question 3</h3>

When clicking on any of the above links AngularJS intercepts and routes me to a completely different page (in my case, a 404-page as there are no routes matching the links.) 单击上面的任何链接时,AngularJS会拦截并将我路由到一个完全不同的页面(在我的情况下是404页,因为没有路由与这些链接匹配。)

My first thought was to create a route matching " /faq/:chapter " and in the corresponding controller check $routeParams.chapter after a matching element and then use jQuery to scroll down to it. 我的第一个想法是创建一个匹配“ / faq /:chapter ”的路由,并在匹配的元素后在相应的控制器中检查$routeParams.chapter ,然后使用jQuery向下滚动到它。

But then AngularJS shits on me again and just scrolls to the top of the page anyway. 但是随后AngularJS再次对我大喊大叫,无论如何仍只是滚动到页面顶部。

So, anyone here done anything similar in the past and knows a good solution to it? 那么,这里有人在过去做过类似的事情并且知道解决方案很好吗?

Edit: Switching to html5Mode should solve my problems but we kinda have to support IE8+ anyway so I fear it's not an accepted solution :/ 编辑:切换到html5Mode应该可以解决我的问题,但是无论如何我们都必须支持IE8 +,所以我担心这不是一个可以接受的解决方案:/


#1楼

参考:https://stackoom.com/question/zjJv/如何在AngularJS中处理锚点哈希链接


#2楼

Here is kind of dirty workaround by creating custom directive that will scrolls to specified element (with hardcoded "faq") 通过创建将滚动到指定元素(带有硬编码“常见问题”)的自定义指令,这是一种肮脏的解决方法

  1. app.directive('h3', function($routeParams) {
  2. return {
  3. restrict: 'E',
  4. link: function(scope, element, attrs){
  5. if ('faq'+$routeParams.v == attrs.id) {
  6. setTimeout(function() {
  7. window.scrollTo(0, element[0].offsetTop);
  8. },1);
  9. }
  10. }
  11. };
  12. });

http://plnkr.co/edit/Po37JFeP5IsNoz5ZycFs?p=preview http://plnkr.co/edit/Po37JFeP5IsNoz5ZycFs?p=preview


#3楼

Try to set a hash prefix for angular routes $locationProvider.hashPrefix('!') 尝试为角度路由$locationProvider.hashPrefix('!')设置哈希前缀

Full example: 完整示例:

  1. angular.module('app', [])
  2. .config(['$routeProvider', '$locationProvider',
  3. function($routeProvider, $locationProvider){
  4. $routeProvider.when( ... );
  5. $locationProvider.hashPrefix('!');
  6. }
  7. ])

#4楼

You're looking for $anchorScroll() . 您正在寻找$anchorScroll()

Here's the (crappy) documentation. 这是(糟糕的)文档。

And here's the source. 这是来源。

Basically you just inject it and call it in your controller, and it will scroll you to any element with the id found in $location.hash() 基本上,您只需注入它并在您的控制器中调用它,它将把您滚动到ID在$location.hash()找到的任何元素。

  1. app.controller('TestCtrl', function($scope, $location, $anchorScroll) {
  2. $scope.scrollTo = function(id) {
  3. $location.hash(id);
  4. $anchorScroll();
  5. }
  6. });
  7. <a ng-click="scrollTo('foo')">Foo</a>
  8. <div id="foo">Here you are</div>

Here is a plunker to demonstrate 这是一个演示的朋克

EDIT: to use this with routing 编辑:与路由一起使用

Set up your angular routing as usual, then just add the following code. 像往常一样设置您的角度路由,然后只需添加以下代码。

  1. app.run(function($rootScope, $location, $anchorScroll, $routeParams) {
  2. //when the route is changed scroll to the proper element.
  3. $rootScope.$on('$routeChangeSuccess', function(newRoute, oldRoute) {
  4. $location.hash($routeParams.scrollTo);
  5. $anchorScroll();
  6. });
  7. });

and your link would look like this: 并且您的链接如下所示:

<a href="#/test?scrollTo=foo">Test/Foo</a>

Here is a Plunker demonstrating scrolling with routing and $anchorScroll 这是一个Plunker,展示了通过路由和$ anchorScroll进行滚动

And even simpler: 甚至更简单:

  1. app.run(function($rootScope, $location, $anchorScroll) {
  2. //when the route is changed scroll to the proper element.
  3. $rootScope.$on('$routeChangeSuccess', function(newRoute, oldRoute) {
  4. if($location.hash()) $anchorScroll();
  5. });
  6. });

and your link would look like this: 并且您的链接如下所示:

<a href="#/test#foo">Test/Foo</a>

#5楼

In my case, I noticed that the routing logic was kicking in if I modified the $location.hash() . 就我而言,我注意到如果修改$location.hash() ,路由逻辑就会启动。 The following trick worked.. 以下技巧有效。

  1. $scope.scrollTo = function(id) {
  2. var old = $location.hash();
  3. $location.hash(id);
  4. $anchorScroll();
  5. //reset to old to keep any additional routing logic from kicking in
  6. $location.hash(old);
  7. };

#6楼

This was my solution using a directive which seems more Angular-y because we're dealing with the DOM: 这是我的解决方案,使用的指令看起来更像Angular-y,因为我们正在处理DOM:

Plnkr over here 在这边

github 的github

CODE

  1. angular.module('app', [])
  2. .directive('scrollTo', function ($location, $anchorScroll) {
  3. return function(scope, element, attrs) {
  4. element.bind('click', function(event) {
  5. event.stopPropagation();
  6. var off = scope.$on('$locationChangeStart', function(ev) {
  7. off();
  8. ev.preventDefault();
  9. });
  10. var location = attrs.scrollTo;
  11. $location.hash(location);
  12. $anchorScroll();
  13. });
  14. };
  15. });

HTML 的HTML

  1. <ul>
  2. <li><a href="" scroll-to="section1">Section 1</a></li>
  3. <li><a href="" scroll-to="section2">Section 2</a></li>
  4. </ul>
  5. <h1 id="section1">Hi, I'm section 1</h1>
  6. <p>
  7. Zombie ipsum reversus ab viral inferno, nam rick grimes malum cerebro. De carne lumbering animata corpora quaeritis.
  8. Summus brains sit​​, morbo vel maleficia? De apocalypsi gorger omero undead survivor dictum mauris.
  9. Hi mindless mortuis soulless creaturas, imo evil stalking monstra adventus resi dentevil vultus comedat cerebella viventium.
  10. Nescio brains an Undead zombies. Sicut malus putrid voodoo horror. Nigh tofth eliv ingdead.
  11. </p>
  12. <h1 id="section2">I'm totally section 2</h1>
  13. <p>
  14. Zombie ipsum reversus ab viral inferno, nam rick grimes malum cerebro. De carne lumbering animata corpora quaeritis.
  15. Summus brains sit​​, morbo vel maleficia? De apocalypsi gorger omero undead survivor dictum mauris.
  16. Hi mindless mortuis soulless creaturas, imo evil stalking monstra adventus resi dentevil vultus comedat cerebella viventium.
  17. Nescio brains an Undead zombies. Sicut malus putrid voodoo horror. Nigh tofth eliv ingdead.
  18. </p>

I used the $anchorScroll service. 我使用了$ anchorScroll服务。 To counteract the page-refresh that goes along with the hash changing I went ahead and cancelled the locationChangeStart event. 为了抵消哈希更改所伴随的页面刷新,我继续进行并取消了locationChangeStart事件。 This worked for me because I had a help page hooked up to an ng-switch and the refreshes would esentially break the app. 这对我有用,因为我将帮助页面连接到ng-switch,并且刷新本质上会破坏应用程序。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/90821
推荐阅读
相关标签
  

闽ICP备14008679号