ui-router 1.0以上的 $stateChangeStart

ui-router transitionhooks

统一控制路由跳转, 前台控制如果没有登录就跳转到登录页面, 当然也可以在后台控制, 如果没有登录就返回对应的错误码, 然后在response中直接跳转

监听$transitions.onStart事件

  1. 监听所有的state

    angular.module('secu',['ui.router'])
        .run(function($rootScope, $transitions, $state) {
            $transitions.onStart({}, function(trans) {
                var stateName = trans.to().name;
                if ((stateName == 'admin.traininer' || stateName == 'admin.miss') && !localStorage.getItem('sessionid')) {
                    return trans.router.stateService.target('login');
                }
            })
        });
  2. 监听指定的state

    angular.module('secu',['ui.router'])
        .run(function($rootScope, $transitions, $state) {
            $transitions.onStart({
                to: function(state) {
                    return (['admin.traininer', 'admin.miss']).indexOf(state.name) > -1;
                }
            }, function(trans) {
                var stateName = trans.to().name;
                if (!localStorage.getItem('sessionid')) {
                    // 下面的代码完成redirect
                    return trans.router.stateService.target('login');
                    // 如果直接返回false 则是放弃当前的state跳转
                    // return false
                }
            })
        });

原文地址:https://www.cnblogs.com/mamimi/p/7809475.html