Angular ui.router. Deep nested routes

时间:2015-06-15 15:07:54

标签: angularjs nested angular-ui-router state

Here is an example to check http://embed.plnkr.co/uVMlkk/preview

When we navigate to 'page2' route there is a 'hey, I'm a subroute' note. But once we navigate anywhere else that note will disappear forever.

The goal is to make some nested states to be shown right away (as a default ones).

I assume there should be some cases using $state.go(), but can't figure it out so far. Any help is highly appreciated.

State definition snippet:

  .state('root.page2.tab', {
    url: '/:tabId',
    templateUrl: 'tpl.page2.tab.html',
    controller: 'Page2TabController'
  })

  .state('root.page2.tab.subroute', {
    url: '',
    templateUrl: 'tpl.page2.tab.subroute.html'
  })

the content of the 'tpl.page2.tab.subroute.html':

hey, I'm a subroute

related controller:

  .controller('Page2TabController', ['$scope', '$state', function($scope, $state) {
    $scope.tabId = $state.params.tabId;
    $state.go('root.page2.tab.subroute');
  }])

2 个答案:

答案 0 :(得分:2)

fixed version

我从'root.page2.tab.subroute'

中删除了网址
.state('root.page2.tab.subroute', {
    //url: '',
    templateUrl: 'tpl.page2.tab.subroute.html'
})

因为父母已经定义了参数tabId

.state('root.page2.tab', {
    url: '/:tabId',
    templateUrl: 'tpl.page2.tab.html',
    controller: 'Page2TabController'
})

我们必须在redicrection中传递该参数:

.controller('Page2TabController', ['$scope', '$state', function($scope, $state) {
    $scope.tabId = $state.params.tabId;
    // instead of this
    // $state.go('root.page2.tab.subroute');
    // we need this
    $state.go('root.page2.tab.subroute', $state.params);
 }])

检查工作的固定版本here

另一种方法 - 使用 redirectTo - 有a working plunker

一种方式,受此启发:

Redirect a state to default substate with UI-Router in AngularJS

可能是添加一个非常智能但很小的重定向代码段:

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

并调整我们的状态:

.state('root.page2.tab', {
    url: '/:tabId',
    templateUrl: 'tpl.page2.tab.html',
    controller: 'Page2TabController',
    redirectTo: 'root.page2.tab.subroute',
})

检查here

答案 1 :(得分:1)

如何处理场景有一个技巧:

  

如果

,父母应该触发一些动作      
      
  • 可以访问,或
  •   
  • 当从父状态的孩子导航返回时再次到达
  •   

在这种情况下,我们可以使用“目标(ui-view)将孩子”作为特殊view的地方,使用特殊的 { {1}} 即可。这将是

    创建父级后
  • 注入该位置
  • 一旦孩子离开,
  • 再次注入该位置。在这种情况下,它将重新初始化。

足够的解释。有a working plunker。有调整状态:

controller

所以,现在我们可以在 .state('root.page2', { url: '/page2', views: { 'content@root': { templateUrl: './tpl.page2.html', controller: 'Page2Controller' }, '@root.page2': { template: '<div></div>', controller: 'RedirectorController' } } })

内部做一些魔术
'RedirectorController'

action here

中查看

详细了解新视图/控制器从其他获取的内容(仅按视图层次结构的范围继承)一个

相关问题