angular.module('frontierApp') .run(['$rootScope', '$state', '$cookieStore', 'userInfoService', function ($rootScope, $state, $cookieStore, userInfoService) { //权限控制开关,true:权限控制有效;false:权限控制将失效,通常本地调试时能够设置为false $rootScope.privilegeStart = true; if ($rootScope.privilegeStart) { $rootScope.$on("$stateChangeStart", function (evt, next, o, current) { if (next.name == "login")return; //受到权限控制的路由 if (next.authority) { var userAuthorityList = userInfoService.getUserAutorityList(); if (userAuthorityList) { //若是当前路由查询到权限code,判断用户是否具备访问权限 var hasAuthority = false; for (var i = 0; i < userAuthorityList.length; i++) { if (next.authority.code == userAuthorityList[i].name) { hasAuthority = true; break; } } //若是用户没有权限,提示用户,并返回欢迎页路由 if (hasAuthority == false) { // $rootScope.messageBox.show("当前用户没有<" + next.authority.page + ">页面访问权限", "WARNING"); $("#noAMsgBoxMsg").html("当前用户没有<" + next.authority.page + ">页面访问权限"); $('#noAMsgBox').modal(); evt.preventDefault(); } } else { var localStorage = window.localStorage; localStorage.removeItem('userInfo'); $cookieStore.remove("userInfo"); $rootScope.messageBox.show("您尚未登录,请登录", "WARNING"); // 中断路由跳转 evt.preventDefault(); $state.go("login"); } } }) } }]) .factory('authorityService', [ '$rootScope', 'userInfoService', function ($rootScope, userInfoService) { var service = { check : function(authorityCode){ if($rootScope.privilegeStart){ var userAuthorityList = userInfoService.getUserAutorityList(); if (!userAuthorityList){ return false; } for (var i = 0; i < userAuthorityList.length; i++) { if (userAuthorityList[i].name == authorityCode) { return true; } } } } } return service ; } ])
controller('RootController',['$rootScope', 'authorityService', function ($rootScope, authorityService) { $rootScope.authorityService = authorityService; } ])
<span ng-if="authorityService.check('A001')" ui-sref="systemUserManage">系统人员管理</span>
这里的路由跳转使用的是angular-ui的ui-router,因此这里监听的路由跳转事件来自ui-router注册。html
这里用的是 ui-router 替换了angular-router。前端
angular.module('myApp.systemUserManage', ['ui.router']) .config(['$stateProvider', function ($stateProvider) { $stateProvider .state('systemUserManage', { url: '/systemUserManage', views: { templateUrl: 'modules/systemUserManage/systemUserManage_view.html', controller: 'SystemUserManageController' }, //受控制的路由配置,权限code与后台返回的用户权限code对应 authority: {code: "A005", page: "帐户管理"} }) }])
有些时候须要在controller中判断某些操做是否具备权限cookie
controller(function($rootScope){ if($rootScope.authorityService.check('A001')){ .... } })