I have one parent state and many childs states. If I want the ui-sref-active
on the parent to work when I am on one of the child I need to do this "hack":
$scope.isActive = function() {
return $state.includes('playLotteries.Index')
|| $state.includes('playLotteries.Group')
|| $state.includes('playLotteries.hunter');
}
This is very ugly way and I have many children so its not seems like good solution. Anyone have another solution for this problem?
[uiSrefActive] : When this selector is used, the class is added when the target state or any child of the target state is active. [uiSrefActiveEq] : When this selector is used, the class is added when the target state is exactly active (the class is not added if a child of the target state is active).
A ui-sref is a directive, and behaves similar to an html href . Instead of referencing a url like an href , it references a state. The ui-sref directive automatically builds a href attribute for you ( <a href=...> </a> ) based on your state's url.
UI-Router is the defacto standard for routing in AngularJS. Influenced by the core angular router $route and the Ember Router, UI-Router has become the standard choice for routing non-trivial apps in AngularJS (1. x).
There is a UI-Router
directive:
ui-sref-active="class-name-to-use"
which from a version 0.2.11 does exactly what we need:
uiSrefActive:
BREAKING CHANGE: Also activate for child states. (bf163ad, closes #818)
uiSrefActiveEq: new directive with old ui-sref-active behavior
so, if we want just assign class for exact match, we have to use this: ui-sref-active-eq="class-name-to-use"
So, why are you experiencing: this is not working?
Because it is working only in conjunction with
ui-sref
directive.
There is a working plunker
These won't work as expected:
// NOT working as expected
<a ui-sref-active="current" href="#/home">
<a ui-sref-active="current" href="#/home/child1">
<a ui-sref-active="current" href="#/home/child2">
But these will be working:
// conjunction ui-sref and ui-sref-active is working
<a ui-sref-active="current" ui-sref="home">
<a ui-sref-active="current" ui-sref="home.child1">
<a ui-sref-active="current" ui-sref="home.child2">
Check it in action here. Example uses this UI-Router 0.2.12 release - and this zip
In that case, we can use another feature of the UI-Router
, the: $urlRouterProvider.when().
There is extended plunker So, with state definition like this:
// when 'home' is selected ... 'home.child2' is used for redirection
$urlRouterProvider.when('/home', '/home/child2');
// instead of 'other' - its 'other.child2' is used... could be any (e.g. other.child1)
$urlRouterProvider.when('/other', '/other/child2');
$urlRouterProvider.otherwise('/home/child2');
So, now, always child is selected (even if navigating to parent) and parent is getting its ui-sref-active
. Check it here
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