Search code examples
ruby-on-railsangularjsangularjs-routing

How to use native anchor links with angularjs


I'm using angularjs on a rather large flat documentation page. The page has some navigation thats designed to use traditional url hash links. The urls look like so:

/documentation/flat#26166276-basic-events

These urls get rewritten once the navigation occurs and i've hit the next page. angular initializes to something like: /documentation/flat#/26166276-basic-events

This breaks the navigation. It seems to work if I am already on the /documentation/flat path and hit one of the hash urls. It gets rewritten but the browser still focus's on the correct section of the page.

However if the the hash url is triggered from a different path the browser will not focus on the correct DOM element as the angularjs rewrite happens.

Edit: this is what the markup for a link looks like

<a href="/documentation/flat#26166276-basic-events">Basic Events</a>

<h1 class="chap-header" id="26166276-basic-events">2.1.0 Basic Events</h1>

Solution

  • This topic was further discussed here:

    How to handle anchor hash linking in AngularJS

    I used a variation from that thread

    if $location.$$url[0]== '#'
            $location.hash($location.$$url.replace('#', ''))
            $anchorScroll()
    

    that basically lets me prefix any anchor links with an additional # and angularjs treats them as traditional anchor