Angular ui-router中$ state.transitionTo()和$ state.go()之间的区别

时间:2014-01-14 03:23:13

标签: javascript angularjs angular-ui-router url-routing angular-ui

在AngularJS中,我发现有时我们会使用$state.transitionTo(),有时我们会使用$state.go()。任何人都可以告诉我他们之间的区别,以及何时应该使用另一个?

2 个答案:

答案 0 :(得分:144)

您指的是AngularUI Router吗?如果是这样,wiki specifies the differences

  

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

     

返回表示转换状态的 Promise

     

转换到新状态的便捷方法。 $state.go在内部调用$state.transitionTo,但会自动将选项设置为{ location: true, inherit: true, relative: $state.$current, notify: true }。这允许您轻松使用绝对路径或相对路径,并仅指定您要更新的参数(同时让未指定的参数从当前状态继承)。

     
     

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

     

返回表示转换状态的 Promise

     

转换到新状态的低级方法。 $state.go()在内部使用transitionTo。在大多数情况下,建议使用$state.go()

答案 1 :(得分:9)

$state.transitionTo转向一个新的州。在大多数情况下,您不必使用它,您可能更喜欢$state.go

它需要options对象中的一些参数:

  • location:如果true将更新位置栏中的网址,则false将不会。如果字符串"replace",将更新网址并替换上一条历史记录。
  • inherit:如果true将从当前网址继承网址参数。
  • relative (stateObject,默认null:使用相对路径(例如'^')进行转换时,定义哪个州是相对的。
  • notify:如果true,则会广播$stateChangeStart$stateChangeSuccess个事件。
  • reload:如果true将强制转换,即使状态或参数没有改变,也称为重新加载相同的状态。

$state.go是一种快捷方式,使用默认选项调用$state.transitionTo

  • locationtrue
  • inherittrue
  • relative$state.$current
  • notifytrue
  • reloadfalse

由于synthax更简单,因此更方便。您只能使用州名称来呼叫它。

$state.go('home');