Angular UI-Router sends 404 root url

I am having a problem causing concern regarding ui-router . Everything works the way I want, where all the bad URLs are sent to state 404 . However, although my default state is correctly displayed when the URL is /#/ , the URL / redirected to /404/ . How can I specify default server as / , and /#/ ?

app.js

 MyApp.config( function ($stateProvider, $urlRouterProvider) { // For any unmatched url, send to 404 $urlRouterProvider.otherwise("/404/"); $stateProvider // Home (default) .state('default', { url: '/', resolve: { ... }, } }); 

Any help is greatly appreciated.

+7
angularjs angular-ui-router
source share
2 answers

I think this will fulfill your needs -

 MyApp.config(function($stateProvider, $urlRouterProvider) { // the known route $urlRouterProvider.when('', '/'); // For any unmatched url, send to 404 $urlRouterProvider.otherwise('/404'); $stateProvider // Home (default) .state('default', { url: '/', resolve: { // ... } // .... }); }); 

I referred to this post . You may need to use regex to process data routes.

Instead of # in your url, you can also use the query string and grab it via $stateParams in state.

Here's how you can do it -

  // .... $stateProvider .state('default', { url: '/?data', templateUrl: 'templates/index.html', controller: 'defaultCtrl' }) 

And then you can use this below to return home with the data -

 var toStateData = { key1: 'value1', key2: 'value2' } $state.go('default', {data: JSON.stringify(toStateData)}); 

You do not need to plan data in $stateParams , but this will allow more parameters with one parameter. In the defaultCtrl controller defaultCtrl you can get the passed query string like this -

 var stateData = JSON.parse($stateParams.data); var key1 = stateData.key1; // .... 
+11
source share

I only wanted to do this with states, so no url provider was involved. I found the following solution, which I think is good:

(sorry this is coffeescript)

  $stateProvider. state('base.public.notFound', url: '^*path' templateUrl: 'views/layouts/404.html' ) 

Put this as your last state and you're done!

+2
source share

All Articles