0

I have a big number of angularjs routes in my app. I would like to set access to these route based on some user permission levels.

angular.module('myApp').run(['$rootScope', 'someAuthFactory', function($rootScope, someAuthFactory) { $rootScope.$on('$stateChangeStart', function (event, toState) { $rootScope.permissions = someAuthFactory.getPermssionLevels(); $rootScope.specialRights = $rootScope.permissions.indexOf('superRole') > -1; ... 

and here is one of my routes:

.state("dashboard.overview", { url: "/dashboard", templateUrl: "app/dashboard.html", resolve: { roles: ['rootScope', function (rootScope) { return $rootScope.specialRights;}] }, 

so this code works, but if i want to add this:

resolve: { roles: ['rootScope', function (rootScope) { return $rootScope.specialRights;}] } 

to every route, it is gonna be duplicate code, or if I want to lookup some other role, it is gonna be boring. Could we make the resolve part much smaller and much cleaner?

3 Answers 3

1

create a variable in config function on top of the routes like this

var resolveRoles = ['rootScope', function (rootScope) { return $rootScope.specialRights;}] } 

and use it in every route like this,

 .state("dashboard.overview", { url: "/dashboard", templateUrl: "app/dashboard.html", resolve: { roles: resolveRoles }, }); 
Sign up to request clarification or add additional context in comments.

Comments

0

You can create a service/factory, which shares $rootScope.specialRights. Just init $rootScope.specialRights in the service in the first resolve of your route e.g.

 .state("dashboard", { url: ... templateUrl: ... resolve: { roles: ['rootScope', function (rootScope) { YourServiceOrFactory.setSpecialRights($rootScope.specialRights); return $rootScope.specialRights }] }, 

And there where you need it

 YourServiceOrFactory.getSpecialRights() 

It does not have to be in other resolves, just in your controller of your route or in your directive/component. Much cleaner and performanter than multiple resovles.

Comments

0

Since you're already setting this property in $rootScope, it is an overkill to use resolve in all of your routes, just to get a variable value, and of course, resolve is not designed for such purposes.

Instead, just inject the $rootScope in your controller and use $rootScope.specialRights in the controller.

Example:

In your controller, service, directive, or component, you can inject the $rootScope like this:

angular.module('your_module') .controller('your_controller', ['$rootScope', function($rootScope) { // Access $rootScope.permissions or $rootScope.specialRights here }]; 

1 Comment

can you give an example?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.