Do any of you know how to nicely handle anchor hash linking in AngularJS?
I have the following markup for a simple FAQ-page
<a href="#faq-1">Question 1</a>
<a href="#faq-2">Question 2</a>
<a href="#faq-3">Question 3</a>
<h3 id="faq-1">Question 1</h3>
<h3 id="faq-2">Question 2</h3>
<h3 id="fa1-3">Question 3</h3>
When clicking on any of the above links AngularJS intercepts and routes me to a completely different page (in my case, a 404-page as there are no routes matching the links.)
My first thought was to create a route matching "/faq/:chapter" and in the corresponding controller check $routeParams.chapter
after a matching element and then use jQuery to scroll down to it.
But then AngularJS shits on me again and just scrolls to the top of the page anyway.
So, anyone here done anything similar in the past and knows a good solution to it?
Edit: Switching to html5Mode should solve my problems but we kinda have to support IE8+ anyway so I fear it's not an accepted solution :/
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.
Docs Search for "Replace method"
None of the solution above works for me, but I just tried this, and it worked,
So I realized I need to notify the page to start with the index page and then use the traditional anchor.
I'm using AngularJS 1.3.15 and looks like I don't have to do anything special.
https://code.angularjs.org/1.3.15/docs/api/ng/provider/$anchorScrollProvider
So, the following works for me in my html:
I didn't have to make any changes to my controller or JavaScript at all.
If you always know the route, you can simply append the anchor like this:
where
route
is the current angular route andanchorID
matches an<a id="anchorID">
somewhere on the pageHere is kind of dirty workaround by creating custom directive that will scrolls to specified element (with hardcoded "faq")
http://plnkr.co/edit/Po37JFeP5IsNoz5ZycFs?p=preview
There is no need to change any routing or anything else just need to use
target="_self"
when creating the linksExample:
And use the
id
attribute in your html elements like this:There is no need to use ## as pointed/mentioned in comments ;-)