13

How do I link to other AngularJS application locations within an anchor A tag? I am using HTML5 hashless mode and would like to avoid having the page actually reload.

For example, in non-HTML5 mode I would do this:

<a href='#/path'>Link</a>

In HTML5 mode I can do this:

<a href='/path'>Link</a>

But this actually causes the browser to reload the new URL. I've also tried using ng-href and also the /#/path syntax but none of them seem to work as I'd like.

How do I properly link from an anchor tag?

3 Answers 3

17

Update:

It seems like this is possible without using $location, you just have to keep the same base link. From the docs:

When you use HTML5 history API mode, you will need different links in different browsers, but all you have to do is specify regular URL links, such as: <a href="/some?foo=bar">link</a>

When a user clicks on this link,

  • In a legacy browser, the URL changes to /index.html#!/some?foo=bar
  • In a modern browser, the URL changes to /some?foo=bar

In cases like the following, links are not rewritten; instead, the browser will perform a full page reload to the original link.

  • Links that contain target element. Example: <a href="/ext/link?a=b" target="_self">link</a>
  • Absolute links that go to a different domain. Example: <a href="http://angularjs.org/"></a>
  • Links starting with '/' that lead to a different base path when base is defined. Example: <a href="/not-my-base/link">link</a>

Old:

You should use the $location service. Inject it into the controller and put it on the $scope (or in a convenience method):

function MainCtrl($scope,$location){
  $scope.goto = function(path){
    $location.path(path);
  }
}
<a ng-click="goto('/path')">Link</a>
Sign up to request clarification or add additional context in comments.

3 Comments

This is what I've done now in a controller on the body element. It just seems a little odd that there is no standard way of doing this.
I haven't had a chance to test that out yet. But I trust that'll it work so I'll accept now.
I prefer to create portable apps. Can I use href and/or ng-href without prior knowledge of base path and html5mode on/off? Or should I always use ng-click in such case?
0

This worked for me in html5mode enabled.

<a ng-href='./path'>Link</a>

Comments

0

Angular Js uses hash prefix followed by exclaimation. Hence if you want to use the anchor tag then have it this way.

Link

https://docs.angularjs.org/tutorial/step_09

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.