Jyina
Jyina

Reputation: 2902

How to define a default route in AngularJS?

I am trying to define a default route when angularjs hits the below url

http://localhost:62831/#/

The default route should go to home page below.

http://localhost:62831/

How can I define it using $urlRouterProvider ? The below line does not seem to be making any difference.

$urlRouterProvider.otherwise('/');

Any suggestions? Thank you!

 appl.config(['$stateProvider', '$urlMatcherFactoryProvider', '$locationProvider', '$urlRouterProvider',
    function ($stateProvider, $urlMatcherFactoryProvider, $locationProvider, $urlRouterProvider) {

        $urlMatcherFactoryProvider.caseInsensitive(true);

        $stateProvider
            .state('home', {
                url: '',
                templateUrl: 'search',
                controller: 'applCtrl'
            })
            .state('person', {
                url: '/person',
                templateUrl: 'Person',
                controller: 'applPersonCtrl'
            })

        $urlRouterProvider.otherwise('/');

        $locationProvider.hashPrefix(''); //it defaults to ! after angularjs 1.5

    }]);

Upvotes: 2

Views: 705

Answers (1)

Luke Hutton
Luke Hutton

Reputation: 10722

You can match on the url of your site (with trailing /) and explicitly go to the home state as follows, while also having a not found url condition:

$urlRouterProvider.otherwise(function ($injector, $location) {
    var $state = $injector.get('$state');
    if ($location.$$url === '' || $location.$$url === '/') {
        $state.go('home');
        return;
    }
    $state.go('notFound'); // some custom not found page
});

Upvotes: 1

Related Questions