How to handle anchor hash linking in AngularJS

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

    Here is kind of dirty workaround by creating custom directive that will scrolls to specified element (with hardcoded "faq")

    app.directive('h3', function($routeParams) {
      return {
        restrict: 'E',
        link: function(scope, element, attrs){        
            if ('faq'+$routeParams.v == attrs.id) {
              setTimeout(function() {
                 window.scrollTo(0, element[0].offsetTop);
              },1);        
            }
        }
      };
    });
    

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

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

    I was trying to make my Angular app scroll to an anchor opon loading and ran into the URL rewriting rules of $routeProvider.

    After long experimentation I settled on this:

    1. register a document.onload event handler from the .run() section of the Angular app module.
    2. in the handler find out what the original has anchor tag was supposed to be by doing some string operations.
    3. override location.hash with the stripped down anchor tag (which causes $routeProvider to immediately overwrite it again with it's "#/" rule. But that is fine, because Angular is now in sync with what is going on in the URL 4) call $anchorScroll().

    angular.module("bla",[]).}])
    .run(function($location, $anchorScroll){
             $(document).ready(function() {
    	 if(location.hash && location.hash.length>=1)    		{
    			var path = location.hash;
    			var potentialAnchor = path.substring(path.lastIndexOf("/")+1);
    			if ($("#" + potentialAnchor).length > 0) {   // make sure this hashtag exists in the doc.                          
    			    location.hash = potentialAnchor;
    			    $anchorScroll();
    			}
    		}	 
     });

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

    This is an old post, but I spent a long time researching various solutions so I wanted to share one more simple one. Just adding target="_self" to the <a> tag fixed it for me. The link works and takes me to the proper location on the page.

    However, Angular still injects some weirdness with the # in the URL so you may run into trouble using the back button for navigation and such after using this method.

    0 讨论(0)
提交回复
热议问题