UI Router: redirect to child state when navigating to abstract parent state

In my music application, I have ng-repeat in the top-level states of my application for creating navigation links. One of the top-level states, called the library, is abstract and has child states (which can be used using tabs). Since I use ng-repeat, the abstract state has a directive ui-sref="library". However, it is not possible to switch to an abstract parent state like this, instead I will need to write ui-sref="library.albums". I cannot do this because of the ng-repeat data coming directly from the state provider. How to set the default child state in the "library" so that at each visit to this state it redirects the child?

Here is a diagram of my installation: enter image description here

+4
source share
2 answers

Unfortunately, you cannot use ui-srefto refer to an abstract state.

you can try something like:

$rootScope.$on('$stateChangeStart', function(event, toState, toParams){
    if(toState.name == 'library'){
        event.preventDefault();
        $state.go('library.albums', toParams);
    }
}

Instead of hard-coding each state redirection, you can do something like:

$stateProvider
    .state('library', {
        url: '/library',
        data: {
            redirect: 'library.albums'
        }
    })
    .state('library.albums', {
        url: '/albums',
        data: {
            redirect: false
        }
    });

$rootScope.$on('$stateChangeStart', function(event, toState, toParams){
    if(toState.data && toState.data.redirect){
        event.preventDefault();
        $state.go(toState.data.redirect, toParams);
    }
}
+1
source

Found this question when I was looking for the same thing, and then found it on the FAQ page on the page w ww wwwwwwwwwwwwwwwwwwwww wwwwwuuuuuuuruuuuuuuua ro. https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions

How to set default child state / index

  • Make an abstract parent state.

    $stateProvider
        .state('library', {
            url: '/library',
            abstract: true,
            template: '<ui-view></ui-view>'
        })
        .state('library.albums', {
            url: '/albums',
            template: '<h1>Albums</h1>'
        });
    
  • , URL-, URL-. , URL- , :

    $urlRouterProvider.when('/library', '/library/albums');
    

URL- GITHUB WIKI, .

+9

Source: https://habr.com/ru/post/1650367/


All Articles