As far as I understand, the usual way to get a notification on a state change is to put a callback on the $stateChangeStart
event, like in this answer .
However, if I understand correctly, I could also attach the $state object to the current scope, as in:
myApp.controller('myAppCtrl', function($scope, $state) {
$scope.$state = $state;
}
This, as far as I understand, would make it possible to watch state details directly from HTML templates, eg (assuming some of my states have a boolean flag .isAdminOnlyState
set to true and I wanted to make the whole page red when displaying them):
<body ng-class='{"everythingInRed": $state.current.data.isAdminOnlyState}'>
What are advantages and disadvantages of this approach, as compared to having a listener function?
It depends if you want to handle something globally or on a single controller/view, the approach you describe is suitable in the case of the latter. However in the code you posted, you need to ensure that myAppCtrl
is always active in your app for that ng-class
to be updated correctly. With routing you tend to have a controller(s) active at a given point in time, not all the time. One could argue that this is a disadvantage of the approach you posted, if you handle a $state
changed event on the $rootScope
you could put $state.current.data.isAdminOnlyState
on the $rootScope
and have it updated accordingly. A disadvantage of putting this on the root scope would be (I imagine) a performance impact, since for every state transition that handler is called, and the code inside the handler is executed, another disadvantage would be that by putting $state.current.data.isAdminOnlyState
on the $rootScope
pollutes the root scope which is usually frowned upon. Having said that, if you intend to have myAppCtrl
active at all times, for example have it be the controller of a section of your main page, such as the navigation bar section for example, it would still be evaluated during every state transition.
Somewhat irrelevant: ui router has a directive to do what you want to that in that code snippet, check out ui-sref-active
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.