Set default child element 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 the condition books.newas a child of the default of the abstract state books, and then, when you press the /booksRedirect ui-router on /books/new?

+4
source share
2 answers

There is a working example

We can use the built-in functions. 1) default is a child state that has an empty URL:

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

2) /books ,

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

:

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

+5

:

$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: , , , url:

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

:

:

$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'
});

:

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 });
      }
    });
}]);
+1

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


All Articles