Is it possible to use anchor links with Angularjs?
I.e.:
<a href="#top">Top</a> <a href="#middle">Middle</a> <a href="#bottom">Bottom</a> <div name="top"></div> ... <div name="middle"></div> ... <div name="bottom"></div>
Thank you
It is mostly used in anchor tags. Anchor tags are the most common HTML tags that take href as a parameter and route users to another website. In Angular, developers should use ng-href instead of href in the anchor tags.
The ng-href directive overrides the original href attribute of an <a> element. The ng-href directive should be used instead of href if you have AngularJS code inside the href value. The ng-href directive makes sure the link is not broken even if the user clicks the link before AngularJS has evaluated the code.
AngularJS Directive's link key defines link function for the directive. Precisely, using link function, we can define directive's API & functions that can then be used by directive to preform some business logic. The link function is also responsible for registering DOM listeners as well as updating the DOM.
The ngInit directive allows you to evaluate an expression in the current scope. This directive can be abused to add unnecessary amounts of logic into your templates. There are only a few appropriate uses of ngInit : aliasing special properties of ngRepeat , as seen in the demo below.
There are a few ways to do this it seems.
Angular provides an $anchorScroll
service, but the documentation is severely lacking and I've not been able to get it to work.
Check out http://www.benlesh.com/2013/02/angular-js-scrolling-to-element-by-id.html for some insight into $anchorScroll
.
Another way I tested out was creating a custom directive and using el.scrollIntoView()
. This works pretty decently by basically doing the following in your directive link function:
var el = document.getElementById(attrs.href); el.scrollIntoView();
However, it seems a bit overblown to do both of these when the browser natively supports this, right?
If you take a look at http://docs.angularjs.org/guide/dev_guide.services.$location and its HTML Link Rewriting section, you'll see that links are not rewritten in the following:
Links that contain target element
Example:
<a href="/ext/link?a=b" target="_self">link</a>
So, all you have to do is add the target
attribute to your links, like so:
<a href="#anchorLinkID" target="_self">Go to inpage section</a>
Angular defaults to the browser and since its an anchor link and not a different base url, the browser scrolls to the correct location, as desired.
I went with option 3 because its best to rely on native browser functionality here, and saves us time and effort.
Gotta note that after a successful scroll and hash change, Angular does follow up and rewrite the hash to its custom style. However, the browser has already completed its business and you are good to go.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With