[英]Angular UI-Router: $state.current is sometimes undefined
我在我的角度應用程序中使用ui.router
,在我的導航欄controller
(包含在多個模板中)中,我編寫了一個簡單的console.log($state.current)
來測試它的行為。
我注意到,有時,在重新加載時,狀態是未定義的:
Object {name: "", url: "^", views: null, abstract: true}
有時它被定義:
Object {url: "/admin", templateUrl: "app/components/admin-dashboard/admin-dashboard.html", controller: "AdminCtrl", controllerAs: "vm", name: "admin-dashboard"}
可能是這種行為的原因是什么?如何保證在加載視圖時定義我的狀態?
在$state.current
獲得正確值的$state.current
是等待ui-router觸發$stateChangeSuccess
事件。 這是你如何做到的:
在Navbar控制器中:
$rootScope.$on('$stateChangeSuccess',
function(event, toState, toParams, fromState, fromParams){
event.preventDefault();
console.log($state.current) // this should now always have a resolved value
})
有關更多詳細信息,請參閱ui-router wiki 。
為什么這種工作方式只針對做console.log($state.current)
是因為,$ state.current有“后”的路線是滿載只有合適的值。 當你在沒有事件的情況下編寫它時,根據你寫它的位置,它可能是命中或錯過。 這就是你得到不一致結果的原因。 正是由於這個原因,ui-router提供了一個成功事件,它承諾該路由已經得到了解決。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.