Victor Victor - 6 months ago 48
AngularJS Question

Home route in ui-router

I use https://github.com/angular-ui/ui-router library. When I try to access index route ('/') I'm redirected to 404. The code:

angular.module('cr').config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/',
templateUrl: 'views/index.html'
});

$urlRouterProvider.otherwise('/404');
});


What's wrong with that code? Although when I use ui-sref="home" it works but the url looks like '/#/' but when a user inputs site name he uses just domain name, like 'mysite.com', not 'mysite.com/#/'

Answer

You've declared how to behave when any unknown/other route is provided - go to /404.

But we also have to define how to behave, when some expected, but not "exact" / "not known" route is accessed, ie. create alias

That's where the .when() could/should be used:

...

// the known route, with missing '/' - let's create alias
$urlRouterProvider.when('', '/');

// the unknown
$urlRouterProvider.otherwise('/404');