如何在嵌套视图上自动加载ui-view?

时间:2015-05-18 06:41:18

标签: angularjs angular-ui-router

我有这样的代码

<a ui-sref="nested.something">something</a>
<div ui-view="nested.something"></div>

如何在不点击ui-sref的情况下加载ui-view?

1 个答案:

答案 0 :(得分:1)

EXTEND - 与OP在上述评论中提供的此plunker相关

州定义是:

.state('store', {
    views: {
      'store': {
        templateUrl: 'store.html'
      }
    }
})

.state('store.detail', {
    views: {
      'store_detail': {
        templateUrl: 'store_detail.html'
      }
    }
})

然后在这个updated plunker我们可以看到这将完成工作

//$urlRouterProvider.otherwise('/store');

$urlRouterProvider.otherwise(function($injector, $location){
   var state = $injector.get('$state');
   state.go('store.detail');
   return $location.path();
});

原因?州没有定义的网址。这有点奇怪。所以,我诚实地建议这样做(the link to such plunker):

  $urlRouterProvider.otherwise('/store/detail');
  //$urlRouterProvider.otherwise(function($injector, $location){
  //   var state = $injector.get('$state');
  //   state.go('store.detail');
  //   return $location.path();
  //});

  $stateProvider

  .state('store', {
    url: '/store',
    views: {
      'store': {
        templateUrl: 'store.html'
      }
    }
  })

  .state('store.detail', {
    url: '/detail',
    views: {
      'store_detail': {
        templateUrl: 'store_detail.html'
      }
    }
  })

a working plunker

<强> ORIGINAL

我们可以使用.otherwise(rule) $urlRouterProvider,记录here

$urlRouterProvider.otherwise('/parent/child');

正如文件所说:

  

<强> otherwise(rule)

     

定义请求无效路由时使用的路径。

因此,这可用于某些默认设置 - 启动&#34;重定向&#34;

.otherwise()甚至可以是一个函数,如下所示:

How not to change url when show 404 error page with ui-router

需要&#39; $ injector&#39;,&#39; $ location&#39;并且可以做更多魔法(在无效或启动路径上)

$urlRouterProvider.otherwise(function($injector, $location){
   var state = $injector.get('$state');
   state.go('404');
   return $location.path();
});

另外,如果我们想在一些嵌套viesw 中填写更多细节,我们可以通过定义多个命名的视图来实现:

  .state('parent.child', { 
      url: "/child",
      views: {
        '' : {
          templateUrl: 'tpl.child.html',
          controller: 'ChildCtrl',
        },
        'nested.something@parent.child' : {
          templateUrl: 'tpl.something.html',
        },
      }
  })

所以,如果tpl.child.html将有这个锚/目标:

<i>place for nested something:</i>
<div ui-view="nested.something"></div>

它将填充 tpl.something.html 内容

检查in action here