If my url contains route parameters, then hash links reroute in angular

前端 未结 4 1192
小蘑菇
小蘑菇 2020-12-31 12:57

If I have a one level route, then the hash links work as expected with no rerouting. However I have some urls that are country/kh and if I try using hash tags such as countr

4条回答
  •  伪装坚强ぢ
    2020-12-31 13:18

    I think I had the same problem that you are having.

    This is how I did it with my github page, http://ngmap.github.io.

    Th site, http://ngmap.github.io, has many pages and each page has lots of anchors, all anchors are coded naturally.

    Without the following code of http://ngmap.github.io/javascripts/app.js, when you click an anchor in your page;

    • it sets $location.path to /anchor. i.el http://url.com/#anchor
    • and it sets $location.hash to ``.

    This behaviour will prevent the page from scrolling down to the hash because simply there is no hash in the url.

    By simply adding $location.hash and scrolling down to that anchor, all should work.

     /**
       * when the location is changed, scroll the page to the proper element.
       * by changing location hash from '' to 'hash', so that it can be used as $anchorScroll
       */
      $rootScope.$on('$locationChangeSuccess', function(newRoute, oldRoute) {
        $location.hash($location.path().replace(/^\//,"")); 
        $anchorScroll();  
      });
    

    With the above code,

    • $location.path remains the same, /anchor
    • $location.hash now becomes anchor

    The only thing you may not like is, the url. It looks little dirty, but I did not mind.

    i.e. http:/ngmap.github.io/basics.html#/map-geolocation#map-geolocation

    Hope it helps

提交回复
热议问题