angularjs ui-router:获取给定状态的子状态列表

时间:2014-10-23 15:38:31

标签: angularjs angular-ui angular-ui-router

你知道在ui-router中获取给定状态的子状态列表的方法吗?

我正在使用ui-router实现一个带有4级深度导航的复杂SPA。

我想为路由器表自动生成的第二级实现导航选项卡界面。

为此,我需要获得给定状态的直接子项列表(可能是抽象状态)。我发现获得状态的唯一方法是执行$state.get()并获取完整的状态列表,但这意味着我必须自己解析子状态,我认为这是代码已经用ui-router写的。

我在这里提出这个问题,以防有任何人有源代码经验,或者知道可以帮助我的插件或模块。同时,如果我找到了什么,我会自己研究并发布结果。

3 个答案:

答案 0 :(得分:9)

我这样做更容易,更快:

var chillin = $state.get().filter(function(cState) { return cState.name.indexOf('parent.state.') === 0 });

答案 1 :(得分:5)

最后,我必须自己实现这个功能。

在具有选项卡界面的抽象路由的控制器中,使用正则表达式过滤状态,利用路由的默认命名约定:

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属性,其中包含呈现标签所需的标题和其他元数据。

我的模板看起来像这样(使用bootstrap):

<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>

答案 2 :(得分:2)

如果你使用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'
            });
      });

在导航控制器中,您可以使用&#34; root&#34;上的children属性。州。例如,我使用它来显示当前状态的所有子项:

angular.module('app')
    .controller('TransportController', function($scope, $state) {
        $scope.items = $state.current.children;     
    });

希望这有帮助。

相关问题