AngularJS - 将父路由重定向到子路由

AngularJS - Redirect parent route to child route

父模板 Accueil(没有内容)有两个子模板 section1section2。这是用于路由的代码:

    $urlRouterProvider.otherwise('/accueil/section1');
    $stateProvider
        .state('accueil', {
            url: '/accueil',
            templateUrl: 'pages/accueil.html'
        })
        .state('accueil.section1', {
            url: '/section1',
            templateUrl: 'templates/section1.html'
        });
        .state('accueil.section2', {
            url: '/section2',
            templateUrl: 'templates/section2.html',
            controller: 'sectionCtrl'
        })

如果我转到 /accueil/secion1/accueil/section2,这很好用。问题是,当我转到 /accueil(没有内容)时,我不知道如何将它重定向到第一个子模板。有什么想法吗?

这里解释了解决方案(UI-路由器中的设计):

  • Angular UI-Router $urlRouterProvider .when not working *anymore*
  • Angular UI-Router $urlRouterProvider .when not working when I click <a ui-sref="...">

我们可以使用 .when(),例如:

$urlRouterProvider
  .when('/accueil', ['$state', 'myService', function ($state, myService) {
        $state.go('accueil.section1');
}])
.otherwise('/app');

但是对于 UI-Router 0.2.13 有一些不同的方法:

var onChangeConfig = ['$rootScope', '$state',
 function ($rootScope, $state) {

  $rootScope.$on('$stateChangeStart', function (event, toState) {    
    if (toState.name === "accueil") { 
      event.preventDefault();
      $state.go('accueil.section1');
    }
  });

}]

这里还有一个关于 0.2.13 的建议https://github.com/angular-ui/ui-router/issues/1584

笨蛋

和例子

  $stateProvider.state('profile' , {
      url: "/about",
      templateUrl: "profile.html",
      redirectTo: 'profile.about'
  });

 app.run($rootScope, $state) {
    $rootScope.$on('$stateChangeStart', function(evt, to, params) {
      if (to.redirectTo) {
        evt.preventDefault();
        $state.go(to.redirectTo, params)
      }
    });
  }

See it in action in a fork of the above plunkr that @yahyaKacem posted:

你真的不想去国家accueil吗?如果是这样,最干净的解决方案是使 parent 状态抽象并将第一个 child 的 url 更改为 '',如下所示:

$urlRouterProvider.otherwise('/accueil');
$stateProvider
    .state('accueil', {
        url: '/accueil',
        templateUrl: 'pages/accueil.html',
        abstract: true
    })
    .state('accueil.section1', {
        url: '',
        templateUrl: 'templates/section1.html'
    });
    .state('accueil.section2', {
        url: '/section2',
        templateUrl: 'templates/section2.html',
        controller: 'sectionCtrl'
    })

现在,如果您简单地导航到 /accueil,您将转到 section1,并附加 /section2 以转到 section2