ui-router stateChangeStart per state

时间:2015-08-03 15:55:30

标签: angularjs angular-ui-router

有没有办法为每个状态指定$stateChangeStart

例如,我可以使用此全局 $stateChangeStart事件来捕获状态更改并拒绝特定的更改:

$rootScope.$on('$stateChangeStart', 
    function (event, toState, toParams, fromState, fromParams) {
        if (!user.isAdmin && toState.name === 'control-panel') {
            event.preventDefault();
        }
    }
);

由于我需要为许多州设置权限,我宁愿做这样的事情:

$stateProvider.state('control-panel', {
    url: '/control-panel',
    template: '<control-panel></control-panel>',
    stateChangeStart: 
        function (event, toState, toParams, fromState, fromParams) {
            if (!user.isAdmin) {
                event.preventDefault();
            }
        }
});

我想在第二个片段中展示的是,我只为一个特定的州定义$stateChangeStart偶数

有办法吗?

编辑:我实施的解决方案就是这样......

$stateProvider.state('control-panel', {
    url: '/control-panel',
    template: '<control-panel></control-panel>',
    authorizeRoles: ['Admin']
});

$rootScope.$on('$stateChangeStart', 
    function (event, toState, toParams, fromState, fromParams) { 
        if (toState.authorizeRoles && toState.authorizeRoles.length &&
            !_.intersection(toState.authorizeRoles, user.roles).length) {
            event.preventDefault();
        }
    }
);

0 个答案:

没有答案