Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I reclaim control of the URL hash-fragment from AngularJS?

Tags:

url

angularjs

I'm using AngularJS, and would like to process a given #hash-fragment in the address-bar. However, —and this is key— I'll not be using the hash-fragment to encode a path. But it seems AngularJS insists on interpreting it that way.

For example, when html5Mode is disabled:

  • A given URL: http://my.domain.com#my-hash
  • is turned into http://my.domain.com/#/my-hash, and
  • $location.hash() will be empty.

And when html5Mode is enabled:

  • A given URL: http://my.domain.com#my-hash
  • is turned into http://my.domain.com/my-hash, and
  • $location.hash() will still be empty.

AngularJS must be thinking: "oh, you have html5, let me remove that hash for you". How considerate…

The only way to get anything from $location.hash() is when the URL has a double hash:

  • For a given URL: http://my.domain.com##my-hash
  • $location.hash() is finally equal to "my-hash", and
  • if also $locationProvider.html5Mode(true) one of the hashes is stripped from the URL.

But I really need a simple single hash character to remain unprocessed. Is this possible?

like image 672
mhelvens Avatar asked Nov 28 '13 14:11

mhelvens


People also ask

How to change URL path in AngularJS?

AngularJs Change Url Example:$location. url('/User/'+userId); will set the current url to the new url example – www.example.com/User/98. You can call the function – changeUrl(userId) on button click.

What is URL hash fragment?

The primary resource is identified by a Uniform Resource Identifier (URI), and the fragment identifier points to the subordinate resource. The fragment identifier introduced by a hash mark # is the optional last part of a URL for a document. It is typically used to identify a portion of that document.

What is html5Mode?

Uses of HTML5 Mode in AngularJS html5Mode is a way to tell the browser that it needs to use HTML5 mode for URLs instead of the older HTTP protocol. This will allow browsers to use features like pushState , which is not supported by older browsers.

Are URL fragments sent to server?

Fragment identifiers are not sent to the server. The hash fragment is used by the browser to link to elements within the same page.


1 Answers

# seems to work well enough on the angular api docs page. So with a little snooping and testing I found that

app.config(function($locationProvider) {
    $locationProvider.html5Mode(true).hashPrefix('!');
});

makes the difference.

like image 60
towr Avatar answered Sep 22 '22 14:09

towr