Angularjs ui router,路由嵌套 父controller执行问题

Posted Alan大bug

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Angularjs ui router,路由嵌套 父controller执行问题相关的知识,希望对你有一定的参考价值。

路由路径设置:structured.text   ;structured是第一层路由,text是第二层路由;

问题如下,当$state.transitionTo路由到第二层是,structured的controller也会执行一次,导致页面控件重新加载刷新。

$state.transitionTo(
    "structured.text", 
    { args : $stateParams },
    { reload: false}
);

查了github看到 https://github.com/angular-ui/ui-router/issues/1612,说此问题已经被fixed,然而设置了reload: stateObj并没有卵用。

I think this makes sense and is a good idea. I‘d like to omit the second reloadState parameter, and overload the existing reload parameter.

  • { reload: true }// reloads all,
  • { reload: ‘foo.bar‘ } // reloads top.bar, and any children
  • { reload: stateObj } // reloads state found in stateObj, and any children

Squash your commits and set your commit message to match the contributor guidelines. If @nateabeleconcurs, I think we‘ll merge this in.

直到看到了https://stackoverflow.com/questions/21105528/difference-between-state-transitionto-and-state-go-in-angular-ui-router

$state.go(to [, toParams] [, options])

Returns a Promise representing the state of the transition.

Convenience method for transitioning to a new state. $state.go calls $state.transitionTointernally but automatically sets options to { location: true, inherit: true, relative: $state.$current, notify: true }. This allows you to easily use an absolute or relative to path and specify only the parameters you‘d like to update (while letting unspecified parameters inherit from the current state).


$state.transitionTo(to, toParams [, options])

Returns a Promise representing the state of the transition.

Low-level method for transitioning to a new state. $state.go() uses transitionTo internally. $state.go() is recommended in most situations.

$state.transitionTo是底层方法,用$state.go是用它实现的,$state.go设置了一些默认参数 ,于是用$state.go试了下,竟然成功;

debug看了下原来是默认options inherit:true和reload:false共同引发的问题:

错误写法1:

$state.transitionTo(
    "structured.text", 
    { args : $stateParams },
    { reload: false}
);    

 原因:路由写了两级,structured的controller会被重复执行

错误写法2:

$state.transitionTo(
      ".text", 
    { args : $stateParams },
    { reload: false}
);   

 原因:relative没有设置和inherit默认又是false

正确写法:

$state.transitionTo(
    ".text", 
    { args : $stateParams },
    { reload: false
        inherit:true,
        relative:"structured"}
);    

  或者

$state.go(
    ".text", 
    { args : $stateParams },
    { reload: false}
);    

果然推荐使用$state.go, 用$state.transitionTo底层方法的话,options要都正确,问题解决,搞了半天事件,这api设计的让人郁闷。

 

 

以上是关于Angularjs ui router,路由嵌套 父controller执行问题的主要内容,如果未能解决你的问题,请参考以下文章

Angularjs ui router,路由嵌套 父controller执行问题

angularjs ui-router 路由简介

深入了解AngularJs-Ui-router

AngularJS“多重路由”嵌套模块——AngularJS“路由”嵌套学习资料教程

angularjs路由ui-router配置

AngularJS UI-Router - 何时使用子/嵌套状态