How to handle anchor hash linking in AngularJS

后端 未结 27 869
后悔当初
后悔当初 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:12

    If you don't like to use ng-click here's an alternate solution. It uses a filter to generate the correct url based on the current state. My example uses ui.router.

    The benefit is that the user will see where the link goes on hover.

    <a href="{{ 'my-element-id' | anchor }}">My element</a>
    

    The filter:

    .filter('anchor', ['$state', function($state) {
        return function(id) {
            return '/#' + $state.current.url + '#' + id;
        };
    }])
    
    0 讨论(0)
  • 2020-11-22 13:15
    <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="faq-3">Question 3</h3>
    
    0 讨论(0)
  • 2020-11-22 13:15

    None of the solution above works for me, but I just tried this, and it worked,

    <a href="#/#faq-1">Question 1</a>
    

    So I realized I need to notify the page to start with the index page and then use the traditional anchor.

    0 讨论(0)
  • 2020-11-22 13:17

    I'm using AngularJS 1.3.15 and looks like I don't have to do anything special.

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

    So, the following works for me in my html:

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

    I didn't have to make any changes to my controller or JavaScript at all.

    0 讨论(0)
  • 2020-11-22 13:18

    Try to set a hash prefix for angular routes $locationProvider.hashPrefix('!')

    Full example:

    angular.module('app', [])
      .config(['$routeProvider', '$locationProvider', 
        function($routeProvider, $locationProvider){
          $routeProvider.when( ... );
          $locationProvider.hashPrefix('!');
        }
      ])
    
    0 讨论(0)
  • 2020-11-22 13:19

    My solution with ng-route was this simple directive:

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

    The html is looking like:

    <a href="" scrollTo="yourid">link</a>
    
    0 讨论(0)
提交回复
热议问题