Angularjs ui router,路由嵌套 父controller執行問題

解決方式來源:https://stackoverflow.com/questions/25316591/angularjs-ui-router-state-reload-child-state-only/25322797#25322797javascript

路由路徑設置:structured.text   ;structured是第一層路由,text是第二層路由;java

問題以下,當$state.transitionTo路由到第二層是,structured的controller也會執行一次,致使頁面控件從新加載刷新。git

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

查了github看到 https://github.com/angular-ui/ui-router/issues/1612,說此問題已經被fixed,然而設置了reload: stateObj並無卵用。angularjs

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.github

  • { 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.api

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

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

Returns a Promise representing the state of the transition.ui

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).this


$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: true}
);    

 緣由:路由寫了兩級,structured的controller會被重複執行

錯誤寫法2:

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

 緣由:relative沒有設置和inherit默認又是false,報錯路由找不到

正確寫法:

$state.go(
    'structured.text',
   {},
   { reload: 'structured.text'}
);

https://github.com/angular-ui/ui-router/issues/1612#issuecomment-77757224 這裏做爲一個bug被fixed,路由設計仍是太蠢...

推薦使用$state.go, 用$state.transitionTo底層方法的話,options要都正確,問題解決,搞了半天研究這個破東西,api設計的讓人鬱悶。

相關文章
相關標籤/搜索