iQ. iQ. -4 years ago 82
AngularJS Question

AngularJS + UI-Router - Manually Type URLs in HTML5 Mode without HashBang

I am currently using AngularJS with UI-Router for state management and express on the back-end.

I currently have hash bang mode enabled and have been trying to find a solution that allows you type URL's without the hash bang manually in the address bar.

So for example instead of typing:

www.mysite.com/#!/page1

I want to able to type

www.mysite.com/page1

I have tried by enable html5Mode:

$locationProvider.html5Mode(true)
.hashPrefix('!');


But it still doesn't work. With the above change, clicking any URL's will re-write and change location from '#!/page1' to '/page1'. Which is great.

However manually entering a URL with '/page1' does not work and gives an invalid path error. If I type it with hash bang included i.e. '#!/page1' then it works and also re-writes the URL as the '/page1' after page load.

So what am I doing wrong here?

My states look like this:

state('login', {
url: '/login',
templateUrl: 'login.html'
}).
state('parent', {
url: '/hello',
abstract: true,
template: '<ui-view/>'
}).
state('parent.home', {
url: '',
controller: 'SomeCtrl',
templateUrl: 'page.html'
}).
state('parent.file', {
url: '/bob',
controller: 'SomeCtrl2',
templateUrl: 'file.html'
})

Answer Source

UPDATE: Your code looks fine to me, i'm going off of experience and think this is a server issue.

There are a few ways you can handle this but as far as I know they are only server side.

using AngularJS html5mode with nodeJS and Express

How do I configure IIS for URL Rewriting an AngularJS application in HTML5 mode?

The reason why you cannot go directly to the route - mywebsite.com/page1 is because the angular app itself (which resides on the index.html page) needs to intercept/direct you to mypage. This is why you see that the page itself is never reloaded, the views are just changing in your app. You can also test this out by refreshing the page too.

You will need implement something server side, that takes your request (IE: /page1) and route all requests to index.html where Angular will take care of the rest.

Additionally: When you use #/page1, you are still requesting your index page, angular recognizes the # and routes accordingly

Edit: Additional Information

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download