Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$location.path() vs $location.hash() in angularjs

Tags:

angularjs

if my present URL is : xzy.com/#/home/new

$location.hash() gives home/new and $location.path also gives home/new

  1. What is the difference in the two?
  2. If inside the controller of home/new I write $location.hash("#/home/new") or $location.path("/home/new") both do not reload the partial but if I do location.href="#/home/new", it reloads the partial. Why is this?

Also, if inside the partial there is a <a href="#/home/new"> that will also reload the partial. Why doesn't setting the path/hash reload the partial?

like image 213
Bhumi Singhal Avatar asked Mar 19 '14 18:03

Bhumi Singhal


2 Answers

There are two parts to the route.

The first "hash" is really there just for browser compatibility and won't show if you are in HTML5 mode.

For example, given this URL:

http://localhost/spa.htm 

If you set:

$location.path('/myPath'); 

you will get:

http://localhost/spa.htm#/myPath

In this case, the "hash" is just for the browser to hold the URL, the method is path. Note also when you call path without a preceding / it is added, i.e. 'myPath' becomes '/myPath'.

If you subsequently set:

$location.hash('myHash'); 

You will get:

http://localhost/spa.htm#/myPath#myHash 

Finally, let's assume you did not set the path first, then you'll get:

http://locahost/spa.htm#/#myHash 

If you are using HTML5 mode, the path is appended without the initial hash.

The first hash is used to append the route, the second is a reference to content on the page. For example, if you use the $anchorScroll service it will respond to what is placed in $location.hash() and not in $location.path().

To summarize:

http://localhost/spa.htm#{path}#{hash}
like image 125
Jeremy Likness Avatar answered Nov 05 '22 19:11

Jeremy Likness


I had a similar question this morning then Google led me here. Inspired by other answers and some Googlings I've done, here is my result:

for example, given a browser url:

http://localhost:8080/test.html#!/testpath#testhash%20with%20someothers

in AngularJS ,

  • url is

    /testpath#testhash

  • path is

    /testpath

    in another word , from left to right ,path starts at the first character in url and ends at the # or ? or the end of url.
    path always start with '/' .so ,if no path is specified ,the path is set as "/" rather than ""

  • hash is

    testhash%20with%20someothers

in another word ,hash starts at the next character of # in url and ends at the end of url

location.href is not implemented in AngularJS. when you say: location.href="#",it behaves like clicking an anchor tag :

<a href="#">click</a>

when invoke the method $location.path,$location.hash as setters, they do change the browser url to match your demands.
And ,why you want AngularJS to RELOAD a page at all? :)

like image 23
wangkaibule Avatar answered Nov 05 '22 19:11

wangkaibule