如何在不重新加载ui-view的情况下更新$ stateParams?角度ui路由器

use*_*283 22 angularjs angular-ui-router

获取上下文,角度,ui-router,没什么特别的,用3个命名的ui-views构建的根视图.所以index.html我们有

<body>
  <div ui-view='left'>
  <div ui-view='center'>
  <div ui-view='right'>
</body>
Run Code Online (Sandbox Code Playgroud)

我的路线看起来像

$stateProvider
 .state('main', {
  url: '/',
  views: {
   'left': {templateUrl: 'foo.html'},
   'center': {templateUrl: 'bar.html'},
   'right': {templateUrl: 'xyz.html'}
  }
 })
 .state('main.b', {
  url: '/b',
  params: { foo: {value: 'bar'} }
  views: { 'right@': {templateUrl: '123.html'} } // I wish to update $stateParams in 'left@' view
 })
 .state('main.c', {
  url: '/c',
  params: ...
  views: { 'left@': ..., 'center@': ..., 'right@': .. }
 });
Run Code Online (Sandbox Code Playgroud)

有没有办法进入b状态更新'中心'和'左'视图中的$ stateParams?我可以使用服务获得它,但我需要添加一个$watch 我需要的变量,它看起来有点hacky对我来说.

进入c状态我实际上可以得到我想要的东西,但视图被重新加载,我希望避免这种行为,因为我在"左"视图中有一个画布.

Lor*_*ual 32

您可以使用以下内容转到特定路由而不重新加载视图:

$state.go('.', {parm1: 1}, {notify: false});
Run Code Online (Sandbox Code Playgroud)

最后一个对象文字表示可以传递给的选项go.如果设置notifyfalse,则实际上会阻止控制器重新初始化.在.一开始是你想去的绝对状态名称或相对路径的状态.

重要的是notify尽管如此.

  • 这在某种程度上仍会导致视图中的所有组件都为$ init,然后立即导致$ destroy,这可能会导致一些严重的性能问题.你可以看看你是否在你的组件中添加一个`console.log()`到`this.$ onInit()`和`this.$ onDestroy()`. (7认同)

Jul*_*ige 19

我认为使用"动态参数"现在是一个更好的解决方案:

当dynamic为true时,更改参数值不会导致进入/退出状态.不会重新获取结算,也不会重新加载视图.

$stateProvider.state('search', {
   url: '/search?city&startDate&endDate',
   templateUrl: 'some/url/template.html',  
   params: {
      city: {
         value: 'Boston',
         dynamic: true
      }
   }
 }
Run Code Online (Sandbox Code Playgroud)

然后:

$state.go('.', {city: 'London'});
Run Code Online (Sandbox Code Playgroud)

https://ui-router.github.io/ng1/docs/latest/interfaces/params.paramdeclaration.html#dynamic https://github.com/angular-ui/ui-router/issues/2709


Mot*_*tin 10

引用@christopherthielen来自https://github.com/angular-ui/ui-router/issues/1758#issuecomment-205060258:

使用notify:false几乎不是一个好主意,现在已弃用.如果必须,请使用reloadOnSearch.

您还可以尝试1.0版本中的动态参数(目前为1.0.0-alpha.3).在您的状态下,将参数配置为动态并实现uiOnParamsChanged回调:

.state('foo', {
  url: '/:fooId',
  params: { fooId: { dynamic: true } },
  controller: function() {
    this.uiOnParamsChanged = function(changedParams, $transition$) {
      // do something with the changed params
      // you can inspect $transition$ to see the what triggered the dynamic params change.
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

有关演示,请查看此plunker:http://plnkr.co/edit/T2scUAq0ljnZhPqkIshB?p = preview