如何获取控制器的州名?

时间:2014-11-14 11:41:05

标签: angular-ui-router

我想知道配置控制器的州名,而不是当前状态。

请注意以下jsfiddle我使用location.hash启动路由并使用我想要避免的解析机制传递所需的状态名称:

http://jsfiddle.net/coma/xzkh3kd5/

location.hash = '/a/b/c';

var template = '<div><h2>{{ current }} vs {{ wanted }}</h2><ui-view></ui-view></div>';

var app = angular.module('app', ['ui.router']);

app.config(function ($stateProvider, $urlRouterProvider) {

    $urlRouterProvider.otherwise('/a');

    $stateProvider
        .state('a', {
            url       : '/a',
            template  : template,
            controller: 'default',
            resolve   : {
                wanted: function () {

                    return 'a';
                }
            }
        })
        .state('a.b', {
            url       : '/b',
            template  : template,
            controller: 'default',
            resolve   : {
                wanted: function () {

                    return 'a.b';
                }
            }
        })
        .state('a.b.c', {
            url       : '/c',
            template  : template,
            controller: 'default',
            resolve   : {
                wanted: function () {

                    return 'a.b.c';
                }
            }
        })
    ;
});

app.controller('default', function ($scope, $state, wanted) {

    $scope.current = $state.current.name;
    $scope.wanted  = wanted;
});

1 个答案:

答案 0 :(得分:0)

嗯,我有一个很好的解决方法,并在使用一些继承配置状态时添加所需的州名:

A)迭代一系列状态配置

http://jsfiddle.net/coma/xzkh3kd5/1/

states.forEach(function (state) {

    var controller = state.config.controller;

    state.config.controller = function ($scope, $controller) {

        $scope.wanted = state.name;

        angular.extend(this, $controller(controller, {
            $scope: $scope
        }));
    };

    $stateProvider.state(state.name, state.config);
});

B)覆盖状态方法

http://jsfiddle.net/coma/xzkh3kd5/2/

var state = $stateProvider.state;

$stateProvider.state = function (name, config) {

    var controller = config.controller;

    config.controller = function ($scope, $controller) {

        $scope.wanted = name;

        angular.extend(this, $controller(controller, {
            $scope: $scope
        }));
    };

    return state.apply($stateProvider, arguments);
};

寻求更好的解决方案。