Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 419
Michael Avatar asked Oct 09 '15 10:10

Michael


2 Answers

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

like image 192
Radim Köhler Avatar answered Oct 31 '22 03:10

Radim Köhler


Try this way:

$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: '',
  templateUrl: 'contents/books-new.html'
});

EDIT: I know that's not very nice, but you can create additional state with same arguments except url:

var booksArgs = {
  url: '',
  templateUrl: 'contents/books-new.html'
};
$stateProvider.state('books.new', booksArgs);
$stateProvider.state('books.new_', angular.extend({}, booksArgs, {
    url: '/new'
}));

Another solution from this post:

In states configuration:

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

On module run:

app.run(['$rootScope', '$state', function($rootScope, $state) {
    $rootScope.$on('$stateChangeStart', function(evt, to, params) {
      if (to.redirectTo) {
        evt.preventDefault();
        $state.go(to.redirectTo, params, { relative: to });
      }
    });
}]);
like image 23
karaxuna Avatar answered Oct 31 '22 04:10

karaxuna