【问题标题】:AngularJS - Redirect parent route to child routeAngularJS - 将父路由重定向到子路由
【发布时间】:2015-05-02 19:00:45
【问题描述】:

父模板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(没有内容)时,我不知道如何将其重定向到第一个子模板。有什么想法吗?

【问题讨论】:

    标签: angularjs angular-ui-router


    【解决方案1】:

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

    我们可以使用.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)
          }
        });
      }
    

    在@yahyaKacem 发布的上述 plunkr 的一个分支中查看它的实际效果:

    【讨论】:

    • 我想我会选择@Joshua Ohana 的回答:D
    【解决方案2】:

    你真的不想去 state accueil 吗?如果是这样,最干净的解决方案是使父状态抽象并将第一个孩子的 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,您将转到第 1 节,然后附加 / 节2 以到达第 2 节

    【讨论】:

    • 感谢您的回答。虽然我不得不将默认路由更改为 .otherwise('/accueil'); 才能正常工作,因为 /accueil/section1 不再存在
    • 我之前的评论现在没有任何意义了:D
    猜你喜欢
    • 1970-01-01
    • 2017-08-10
    • 2018-10-22
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 2017-08-21
    • 2020-06-15
    • 1970-01-01
    相关资源
    最近更新 更多