Reputation: 147
I am attempting to dynamically draw a nested navigation structure using the AngularJS UI router library with StateHelper (see example JSON below).
I am struggling with finding a way to access the array of children in my nested template. Is there a way to access the state associated with the current template / controller?
I attempted using $state.current
, but this does not work as it resolves to the same value (rightly so) at each nested level. I need to be able to access the "current" state, i.e. the one being rendered at that moment in time.
Any ideas very welcome!!
nested.html
<ul class="nav nav-tabs">
<li ng-repeat="tab in children" ui-sref-active="active">
<a data-ui-sref="{{tab.name}}" ng-bind-html="tab.name"></a>
</li>
</ul>
<br />
<div data-ui-view></div>
Example navigation
[{
"name": "root",
"template": "<ui-view/>",
"children": [
{
"name": "a",
"url": "/a",
"templateUrl": "static/partials/nested.html",
"children": [{
"name": "1",
"url": "/1",
"templateUrl": "static/partials/nested.html",
"children": [{
"name": "i",
"url": "/i",
"template": "Content for root.a.1.i"
}, {
"name": "ii",
"url": "/ii",
"template": "Content for root.a.1.ii"
}]
}, {
"name": "2",
"url": "/2",
"templateUrl": "static/partials/nested.html",
"children": [{
"name": "i",
"url": "/i",
"template": "Content for root.a.2.i"
}, {
"name": "ii",
"url": "/ii",
"template": "Content for root.a.2.ii"
}]
}
]
}, {
"name": "b",
"url": "/b",
"template": "Content for root.b"
}]
}]
Upvotes: 1
Views: 295
Reputation: 4539
There is a data field named $uiView
attached to the ui-view element, it contains the view name and the associated state
. You can get the state
like this:
elem.closest('[ui-view]').data('$uiView').state
or even
elem.inheritedData('$uiView').state
So, in your controller
:
.controller('State1Ctrl', function ($state) {
console.log(elem.closest('[ui-view]').data('$uiView').state); // state1
});
See if this helps you. Also using ui-sref
, it is possible:
<ul class="nav nav-tabs">
<li ng-repeat="tab in children" ng-class="{ active: $state.current == 'tab.name' }">
<a data-ui-sref='tab.name' ng-bind-html="tab.name"></a>
</li>
</ul>
Here tab.name being assumed to contain your state.
Upvotes: 2