Jymbo Jymbo - 2 months ago 14
Javascript Question

How to preset state of ui-router programmatically

I have implemented an

md-sidenav
which allows to navigate to different html templates by selecting it in the sidenav list.

What I am trying is to preselect the first item in my
md-sidenav
when the whole html page is loaded. So I don't have to press the first button to get routed to the first template by ui-router.

HTML:

<md-sidenav flex class="sidenav md-whiteframe-z2 md-sidenav-left" md-component-id="left">
<md-button ng-repeat-start="item in menuItems"
flex layout="column" layout-align="center center"
ng-click="selectItem(item)"
ui-sref="{{item.sref}}">
<div class="md-tile-content">
{{item.name}}
</div>
</md-button>
<md-divider ng-repeat-end></md-divider>
</md-sidenav>

<md-content flex class="md-padding page-content">
<div ui-view></div>
</md-content>


Controller:

menuItems = [
{
name: 'personA',
icon: 'person',
sref: '.personA'
},
{
name: 'personB',
icon: 'person',
sref: '.personB'
},
{
name: 'personC',
icon: 'person',
sref: '.personC'
}
];

function toggleItemsList() {
$mdSidenav('left').toggle();

}

function selectItem (item) {
self.title = item.name;
self.toggleItemsList();
}


The stateProvider of ui-router:

$stateProvider
.state('.personA', {
url:...
controller:...
templateUrl:...
})
.state('.personB', {
url: ...
controller:...
templateUrl: ...
})
.state('.personC', {
url: ...
controller: ...
templateUrl: ...
});


I know the parameter of the first template by using
ng-init
and
$first
but for some reason the ui-router doesn't get triggered so no html template is loaded. I think I need to manipulate
ui-sref="{{item.sref}}"
but not sure about this.

Answer Source

To programmatically set a default state with ui-router you can use $urlRouterProvider:

$urlRouterProvider.otherwise('/yourDefaultStateUrl');

Example:

function myConfig($stateProvider, $urlRouterProvider){
    $stateProvider
    .state('home', {
        url: '/home', 
        templateUrl:... 
    })
    .state('about', {
        url: '/home', 
        templateUrl: ...
    });

    $urlRouterProvider.otherwise('/home'); //Home as default state
}