I'm using ui.router in my angular app, and in my navbar controller (which is included in more than one template) I wrote a simple console.log($state.current) to test it's behavior.
I've noticed that, sometimes, upon 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 might be the cause of this behavior and how can I guarantee that my state is defined when the view is loaded?
Surest way to get the right value in $state.current is to wait for the $stateChangeSuccess event to be fired by 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
})
Refer ui-router wiki for more details.
Why this works as against only doing a console.log($state.current) is because,
$state.current has the right value only 'after' the route is fully loaded. When you write it without the event, depending on where you write it, it can be a hit or miss. That's why you were getting inconsistent results. It's exactly for this reason that ui-router provides a success event, which promises that route has definitely been resolved.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With