How to handle anchor hash linking in AngularJS

后端 未结 27 922
后悔当初
后悔当初 2020-11-22 12:22

Do any of you know how to nicely handle anchor hash linking in AngularJS?

I have the following markup for a simple FAQ-page



        
27条回答
  •  太阳男子
    2020-11-22 13:05

    $anchorScroll works for this, but there's a much better way to use it in more recent versions of Angular.

    Now, $anchorScroll accepts the hash as an optional argument, so you don't have to change $location.hash at all. (documentation)

    This is the best solution because it doesn't affect the route at all. I couldn't get any of the other solutions to work because I'm using ngRoute and the route would reload as soon as I set $location.hash(id), before $anchorScroll could do its magic.

    Here is how to use it... first, in the directive or controller:

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

    and then in the view:

    Text
    

    Also, if you need to account for a fixed navbar (or other UI), you can set the offset for $anchorScroll like this (in the main module's run function):

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

提交回复
热议问题