kovac
kovac

Reputation: 5389

How to activate a state on page load for angular ui-sref?

I'm using the following ui-router configuration. So, when the user clicks on a tab, the tab is highlighted correctly as expected. However, no tab is highlighted when the page first loads and the user has to click on a tab for its state to get activated. I would like the home state to be the active tab when the page first loads. How can I achieve this?

 angular.module("app", ['app.home', 'app.page1', 'app.page2', 'app.page3'])

.config(function($stateProvider, $urlRouterProvider) {

$urlRouterProvider.otherwise('home');

$stateProvider

.state('home', {
    url: '/',
    views: {
        'MainContentPlaceHolder': {
            templateUrl: '../Home/_Layout.html'
        }
    }
})

.state('page1', {
    url: '/page1',
    views: {
        'MainContentPlaceHolder': {
            templateUrl: '../Page-1/_Layout.html'
        }
    }
})

.state('page2', {
    url: '/page2',
    views: {
        'MainContentPlaceHolder': {
            templateUrl: '../Page-2/_Layout.html'
        }
    }
})

.state('page3', {
    url: '/page3',
    views: {
        'MainContentPlaceHolder': {
            templateUrl: '../Page-3/_Layout.html'
        }
    }
});
})

My HTML markup is:

<body>
<section id="NavBar">
    <nav class="navbar navbar-inverse navbar-static-top">
        <div class="container-fluid">
            <div class="navbar-header">
                <a class="navbar-brand" ui-sref="home"><span class="glyphicon glyphicon-home" aria-hidden="true"></span></a>
            </div>
            <ul class="nav navbar-nav">
                <li ui-sref-active="active"><a ui-sref="home">Home</a></li>
                <li ui-sref-active="active"><a ui-sref="page1">Page 1</a></li>
                <li ui-sref-active="active"><a ui-sref="page2">Page 2</a></li>
                <li ui-sref-active="active"><a ui-sref="page3">Page 3</a></li>
            </ul>
        </div>
    </nav>
</section>
    <section id="ContentPlaceHolder" ui-view="MainContentPlaceHolder"></section>
</body>

Upvotes: 1

Views: 942

Answers (1)

kovac
kovac

Reputation: 5389

Okay so I managed to figure out the issue. It was a syntax error at the third line which should change from

$urlRouterProvider.otherwise('home');

to

$urlRouterProvider.otherwise('/');

I had thought that $urlRouter.otherwise() takes in the state as parameter. It should in fact be the redirect url.

Upvotes: 1

Related Questions