Mark Mark - 9 days ago 7
Javascript Question

Replace URL in Angular environment

I need to modify the URL after opening a new window and navigating to a state.

My starting page looks like this:

localhost:8000/startpage.html
.

When it loads the URL becomes

localhost:8000/startpage.html#/
.

In the new window I am navigating to a new state:

localhost:8000/startpage.html#/newstate
.

What I want is to have the URL looking like this:

localhost:8000/startpage.html?project=1#/newstate
.

I am getting almost correct results except that instead of replacing the URL completely it adds

?project=1#/newstate
to
localhost:8000/startpage.html#/
.

So the result is something like this:

localhost:8000/startpage.html#/%3Fproject=903%23/newstate


while what I need is:

localhost:8000/startpage.html?project=903#/newstate


Here is some relevant code:

if ($window.history.replaceState) {
var newUrl = '?project=903' + '#/case';
$location.path(newUrl);
$location.replace();
};


Seems to me I am having two problems. Extra '#/' after '.html' and the URL is encoded. Because even if I remove extra '#/' it still does not work unless I replace encoded characters with real ones.
Please help.

Thanks

Answer

I think you are using the wrong method. You want to be using $location.url which will allow you to set the path, query, and hash values all at once. But you may be better off setting the query and hash separately because you don't need to change the entire url.

$location.search('project', '903');
$location.hash('case');

I removed the / from the hash because it isn't necessary.

Also, by default angular uses hash mode to navigate its routes. If you want to supply a hash I think you will need to turn that behavior off.

$locationProvider.html5Mode(true);

Set that in your application's configuration.

Here is a good article: https://scotch.io/tutorials/pretty-urls-in-angularjs-removing-the-hashtag