Skip to content

Instantly share code, notes, and snippets.

@hsrob
Created May 11, 2015 12:30
Show Gist options
  • Save hsrob/4169465f93a3bc69b9c1 to your computer and use it in GitHub Desktop.
Save hsrob/4169465f93a3bc69b9c1 to your computer and use it in GitHub Desktop.
Resolve ui-router testing
<body ng-app="webapp">
<div ui-view>
</div>
</body>
var app = angular.module('webapp', ['ui.router'])
.constant('USER_ROLES', {
admin: 'admin',
manager: 'manager',
employee: 'employee'
})
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider.state('home', {
url: '/',
controller: 'HomeCtrl',
template: '<p>HomeCtrl</p><p><a ui-sref="home.adminonly">Admin Only Area</a></p><div ui-view></div>',
resolve: {
//Resolve entries are resolved at link-time
authorizedRoles: ['USER_ROLES', function(USER_ROLES) {
return [USER_ROLES.admin, USER_ROLES.manager, USER_ROLES.employee];
}]
}
})
.state('home.adminonly', {
url: '/adminonly',
template: '<p>Only admins are allowed here</p>',
resolve: {
authorizedRoles: function(USER_ROLES) {
return [USER_ROLES.admin];
}
}
});
$urlRouterProvider.otherwise("/");
});
app.service('authService', function(USER_ROLES) {
//fake current roles
var userRoles = [USER_ROLES.employee];
this.isAuthorized = function(requiredRoles) {
angular.forEach(requiredRoles, function(rr) {
if (!userRoles.indexOf(rr)) return false;
})
}
})
app.run(function($rootScope, $state, USER_ROLES, authService) {
$rootScope.$on('$stateChangeStart',
function(event, toState, toParams, fromState, fromParams) {
//here's where you would call event.preventDefault() if you knew the user wasn't authorized
});
$state.go('home');
})
app.controller('HomeCtrl', function($scope, $state, authorizedRoles) {
console.log('HomeCtrl');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment