Angular UI-Router: $ state.current is sometimes undefined

I am using ui.router

angular in my application and in my navigator controller

(which is included in more than one template) I wrote a simple one console.log($state.current)

to test its behavior.

I noticed that sometimes on reload the state is undefined:

Object {name: "", url: "^", views: null, abstract: true}

      

and sometimes it is defined:

Object {url: "/admin", templateUrl: "app/components/admin-dashboard/admin-dashboard.html", controller: "AdminCtrl", controllerAs: "vm", name: "admin-dashboard"}

      

What could be causing this behavior and how can I ensure that my state is determined when the view is loaded?

+3


source to share


1 answer


The best way to get the correct value in $state.current

is to wait for the event to $stateChangeSuccess

be fired using ui-router. Here's how you can do it:

In your Navbar controller:

$rootScope.$on('$stateChangeSuccess', 
function(event, toState, toParams, fromState, fromParams){ 
    event.preventDefault(); 
    console.log($state.current)  // this should now always have a resolved value
})

      



See the ui-router wiki for details .

Why does this work versus what it does just console.log($state.current)

because, $ state.current only has the correct value after the route is fully loaded. When you write it without an event, depending on where you write it, it can be hit or miss. This is why you got inconsistent results. It is for this reason that ui-router provides a success event that promises are definitely allowed.

+7


source







All Articles