How to handle anchor hash linking in AngularJS

后端 未结 27 1302
后悔当初
后悔当初 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: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;
          }
        });
    }
    

提交回复
热议问题