Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: How to have default nested state using UI Router?

I currently have a root index.html with a single ui-view which gets replaced depending on which "page" the user is on, e.g. Books, Games etc. Taking the Books page as an example, this view has content that I'd like to display on all pages which are part of the "Books" space, but the central content will differ depending on if the user is on the Books "homepage" or looking at a specific book. To facilitate this, my books.html has a nested state which either includes books_list.html or books_detail.html.

The url structure I'd like to have is:

  • /books - Shows left/right sidepanels plus a list of books in the middle of the page.
  • /books/1 - Shows left/right sidepanels plus the details for the book with ID 1 in the middle of the page (list of books is not displayed).

How can I set up my states to have the books.html template AND books_list.html template in the nested view when navigating to /books, but have books.html AND books_detail.html when navigating to /books/1 ?

I'm currently getting round this problem by having a "home" sub-state, but this means that I have to have /books/home, and /books displays no central content so is currently useless.

.state('books', {
    url: '/books',
    templateUrl: CONFIG.static_url + '/html/books.html',
    ...
})
.state('books.home', {
    url: '/home',
    templateUrl: CONFIG.static_url + '/html/books_list.html',
    ...
})
.state('books.detail', {
    url: '/:bookId',
    templateUrl: CONFIG.static_url + '/html/books_detail.html',
    ...
})
like image 713
thor Avatar asked Nov 28 '14 17:11

thor


1 Answers

I achieved what I needed by declaring an abstract state:

.state('books', {
    abstract: true,
    url: '/books',
    templateUrl: CONFIG.static_url + '/html/books.html',
    ...
})
.state('books.home', {
    url: '',
    templateUrl: CONFIG.static_url + '/html/books_list.html',
    ...
})
.state('books.detail', {
    url: '/:bookId',
    templateUrl: CONFIG.static_url + '/html/books_detail.html',
    ...
})

This means that /books loads both 'books' and 'books.home' states, and /books/1 loads both 'books' and 'books.detail' states, which is what I needed.

like image 59
thor Avatar answered Oct 21 '22 05:10

thor