How to handle anchor hash linking in AngularJS

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

    There is no need to change any routing or anything else just need to use target="_self" when creating the links

    Example:

    <a href="#faq-1" target="_self">Question 1</a>
    <a href="#faq-2" target="_self">Question 2</a>
    <a href="#faq-3" target="_self">Question 3</a>
    

    And use the id attribute in your html elements like this:

    <h3 id="faq-1">Question 1</h3>
    <h3 id="faq-2">Question 2</h3>
    <h3 id="faq-3">Question 3</h3>
    

    There is no need to use ## as pointed/mentioned in comments ;-)

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

    On Route change it will scroll to the top of the page.

     $scope.$on('$routeChangeSuccess', function () {
          window.scrollTo(0, 0);
      });
    

    put this code on your controller.

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

    In my mind @slugslog had it, but I would change one thing. I would use replace instead so you don't have to set it back.

    $scope.scrollTo = function(id) {
        var old = $location.hash();
        $location.hash(id).replace();
        $anchorScroll();
    };
    

    Docs Search for "Replace method"

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

    I could do this like so:

    <li>
    <a href="#/#about">About</a>
    </li>
    
    0 讨论(0)
  • 2020-11-22 13:10
    <a href="/#/#faq-1">Question 1</a>
    <a href="/#/#faq-2">Question 2</a>
    <a href="/#/#faq-3">Question 3</a>
    
    0 讨论(0)
  • 2020-11-22 13:11

    I got around this in the route logic for my app.

    function config($routeProvider) {
      $routeProvider
        .when('/', {
          templateUrl: '/partials/search.html',
          controller: 'ctrlMain'
        })
        .otherwise({
          // Angular interferes with anchor links, so this function preserves the
          // requested hash while still invoking the default route.
          redirectTo: function() {
            // Strips the leading '#/' from the current hash value.
            var hash = '#' + window.location.hash.replace(/^#\//g, '');
            window.location.hash = hash;
            return '/' + hash;
          }
        });
    }
    
    0 讨论(0)
提交回复
热议问题