How to preset state of ui-router programmatically

人走茶凉 提交于 2019-12-24 08:16:42

问题


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.


回答1:


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
}


来源:https://stackoverflow.com/questions/43699699/how-to-preset-state-of-ui-router-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!