Search code examples
javascriptangularjsangular-ui-routerurl-routing

Set default child of abstract nested state in ui-router


I use ui-router.
Here are my nested states:

$stateProvider
.state('books', {
  abstract: true,
  url: '/books',
  controller: 'BooksCtrl',
  templateUrl: 'contents/books.html'
})
.state('books.top', {
  url: '/top',
  templateUrl: 'contents/books-top.html'
})
.state('books.new', {
  url: '/new',
  templateUrl: 'contents/books-new.html'
});

How can I set books.new state to be default child of the books abstract state, so then when you hit /books ui-router redirects to /books/new?


Solution

  • There is a working example

    We can use built in features. 1) default is such child state which has empty url:

    $stateProvider
        .state('books', {
          abstract: true,
          url: '/books/new',
          controller: 'BooksCtrl',
          ..
        })
        .state('books.new', {
          //url: '/new',
          url: '',
          ...
        })
        .state('books.top', {
          url: '^/books/top',
          ...
        });
    

    And 2) to keep /books in place, we can use redirection

      $urlRouterProvider.when('/books', '/books/new');
    

    And these links will work as expected:

    // href
    <a href="#/books">
    <a href="#/books/new">
    <a href="#/books/top">
    //ui-sref
    <a ui-sref="books.top">
    <a ui-sref="books.new">
    

    Check it here