简体   繁体   中英

angularjs - load different controllers/js files based on users' access levels

I'm working on a web app where users have different access levels. Each access level has different sets of controllers/views.

I'm using ngRoute and ng-view . Each controller has its own JS file and it also contains the route mapping information for just that controller. Each controller looks like:

angular.module('MainApp', ['ngRoute'])

 .controller('ContollerX', function() {
 })

.config(function($routeProvider) {
  $routeProvider
  .when('/ControllerXURL', {
    templateUrl: 'ViewX.html',
    controller: 'ControllerX'
  });
});

(Not sure if it's the best practice)

I don't want to load all the controllers upfront. Is it possible to load just the controllers a user need based on a user's access level, which is determined after he/she logs in (user access level data returned from backend)? What would be the best approach?

I'm thinking to load the controller scripts dynamically, like inserting the script tag. Will it work? Does AngularJs have any built-in function for this?

There is a much easier way to achieve what you want using resolve property in route definition object. The resolve returns a promise and the route to the controller using resolve will be redirected only when this promise is resolved. You can use this to redirect to required view.

Say you have 2 views: AuthorizedUsers.html and UnauthorizedUsers.html and corresponding controllers AuthorizedUsersController and UnauthorizedUsersController. You can have your route definition for these views as below:

 angular
   .module('MainApp', ['ngRoute'])
   .controller('AuthorizedUsersController', function(auth) {
   })
   .controller('UnauthorizedUsersController', function() {
   })
   .config(function($routeProvider) {
     $routeProvider
       .when('/authorizedusers', {
         templateUrl: 'AuthorizedUsers.html',
         controller: 'AuthorizedUsersController',
         resolve: {
           auth: function ($q, $location) { 
             var defer = $q.defer();
             if (isAuthorized) {
               defer.resolve();
             } else {
               $location.path('/unauthorized');
               defer.reject();
             }
             return defer.promise;
           }
         }
       })
       .when('/unauthorizedusers', {
         templateUrl: 'UnauthorizedUsers.html',
         controller: 'UnauthorizedUsersController'
       });
   });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM