[英]angularjs ui-router: Get list of child states of a given state
您是否知道ui-router中获取给定状态的子状态列表的方法?
我正在使用ui-router实现可能具有4级深度导航的复杂SPA。
我想为从路由器表自动生成的第二级实现导航选项卡界面。
为此,我需要获取给定状态(也许是抽象状态)的直接子级的列表。 我发现获取状态的唯一方法是执行$state.get()
并获取状态的完整列表,但这意味着我必须自己解析子状态,而我认为那是ui-router中已经编写的代码。
如果有人在源代码方面有经验,或者知道可以帮助我的插件或模块,我将在此处提出。 同时,如果有发现,我将自己进行研究并发布结果。
我这样做更容易,更快捷:
var chillin = $state.get().filter(function(cState) { return cState.name.indexOf('parent.state.') === 0 });
最后,必须自己实现功能。
在具有tab接口的抽象路由的控制器中,使用正则表达式利用路由的默认命名约定对状态进行过滤:
var routeName='Root.Parent'; // this is the "actual" route
// this regex is going to filter only direct childs of this route.
var secondRouteOnlyRegex = new RegExp(routeName + "\.[a-z]+$", "i");
var states = $state.get();
// this uses lodash to filter the states based on the regex
var navLinks = _.filter(states, (s) => {
return secondRouteOnlyRegex.test(s.name) && !s.abstract;
});
$scope.tabs = navlinks;
我的路线定义具有一个data
属性,其中包含标题和呈现选项卡所需的其他元数据。
我的模板看起来像这样(使用引导程序):
<ul class="nav nav-tabs">
<li ng-repeat="state in tabs" ui-sref-active="active">
<a href="{{state.url}}" ui-sref="{{state.name}}">{{state.data.title}}</a>
</li>
</ul>
如果您使用stateHelper ,它使您可以这样注册状态(来自stateHelper自述文件):
angular.module('myApp', [ 'ui.router', 'ui.router.stateHelper' ])
.config(function(stateHelperProvider){
stateHelperProvider
.state({
name: 'root',
templateUrl: 'root.html',
children: [
{
name: 'contacts',
template: '<ui-view />',
children: [
{
name: 'list',
templateUrl: 'contacts.list.html'
}
]
},
{
name: 'products',
templateUrl: 'products.html',
children: [
{
name: 'list',
templateUrl: 'products.list.html'
}
]
}
]
})
.state({
name: 'rootSibling',
templateUrl: 'rootSibling.html'
});
});
然后,您可以在导航控制器中使用“ root”状态下的children
属性。 例如,我正在使用它来显示当前状态的所有子级:
angular.module('app')
.controller('TransportController', function($scope, $state) {
$scope.items = $state.current.children;
});
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.