Observing state changes in angular-ui-router

As far as I understand, the usual way to get notified of a state change is to include a callback in an event $stateChangeStart

, such as in this response .

However, if I understood correctly, I could also bind the $ state object to the current scope, as in:

myApp.controller('myAppCtrl', function($scope, $state) {
    $scope.$state = $state;
}

      

This, as far as I understand, will allow viewing state data directly from HTML templates, for example. (assuming some of my states have a boolean flag .isAdminOnlyState

set to true and I wanted to make the whole page red when displayed):

<body ng-class='{"everythingInRed": $state.current.data.isAdminOnlyState}'>

      

What are the advantages and disadvantages of this approach compared to a listener function?

+3


source to share


1 answer


It depends on whether you want to handle something globally or on a single controller / view, the approach you described is fine for the latter. However, in your posted code, you need to make sure it is myAppCtrl

always active in your application for this one to ng-class

be updated correctly. With routing, you usually have the controller (s) active at a given time, not all the time. Arguably this is a flaw in the approach you posted, if you handle an event $state

changed to $rootScope

, you can put $state.current.data.isAdminOnlyState

in$rootScope

and update it accordingly. The downside of using this parameter in the root area will (I think) have a performance impact, since for every state transition called by the handler and code inside the handler, another drawback is that putting $state.current.data.isAdminOnlyState

on $rootScope

pollutes the root area that is usually frowned upon. Having said that, if you intend to maintain permanently myAppCtrl

, for example, whether it is a master page section controller, such as a navigation bar section, it will still be evaluated during every state transition.



Somewhat inappropriate: ui router has a directive to do what you want in this piece of code, check ui-sref-active

.

+1


source







All Articles