AngularJS, ui.router, load template and controller based on user role

user3596298 picture user3596298 · May 2, 2014 · Viewed 17.8k times · Source

I have developed a Single Page App that uses a REST api. Users are required to login to access the application. When a user logs in they are redirected to /dashboard. On this URL / route, I would like to load a different template and controller based on the role of the user (e.g. normal user or admin user).

I have looked at https://github.com/angular-ui/ui-router/wiki under the templates section but none of the options support what I am trying to achieve.

  • By using templateUrl and function (stateParams) I am not able to inject the service that helps me to determine the user role so that I can load the template, e.g. views/user/dashboard.html or views/admin/dashboard.html
  • By using templateProvider I am to inject the service that helps me to determine the user role, but how do I then load the template?

Any solution should also load different controllers based on the user role, for example UserDashboardController or AdminDashboardController.

So essentialy what I need is a single route that loads a different template AND controller based on a user role variable that is set in a service when a user logs in.

Am I thinking along the right lines, or should I be implementing another solution?

Any help on this would be greatly appreciated.

Answer

miensol picture miensol · Aug 31, 2014

Loading template and controller based on user role

While technically ui-router templateUrl function does not support injecting services you can use templateProvider to inject service that holds role variable or loads it asynchronously and then use $templateFactory to return HTML content. Consider following example:

var app = angular.module('app', ['ui.router']);

app.service('session', function($timeout, $q){
    this.role = null;

    this.loadRole = function(){
        //load role using axax request and return promise
    };
});

app.config(function($stateProvider, $urlRouterProvider){
    $stateProvider.state('dashboard', {
        url: '/dashboard',
        templateProvider: function(session, $stateParams, $templateFactory){
          return session.loadRole().then(function(role){
              if(session.role == 'admin'){
                return $templateFactory.fromUrl('/admin/dashboard.html', $stateParams);
              } else {
                return $templateFactory.fromUrl('/user/dashboard.html', $stateParams);
              }
          });
        }
      });

    $urlRouterProvider.otherwise('/dashboard');
});

As for controller you can either state that you would like to use specific controller inside root element of each template with ng-controller. Or similarly you can use controllerProvider option to inject service that will already have role resolved by templateProvider. Take a look at following example of controllerProvider option inside ui-router state definition:

controllerProvider: function(session){
  if(session.role == 'admin'){
    return 'AdminCtrl';
  } else {
    return 'UserCtrl';  
  }
}

Of course you can remove duplicates from this code easily and define a more accessible micro DSL to make defining different rules for particular roles and views easier.

The following demo should help you understand the code.

Is this a right approach?

As usually this greatly depends on context. To help you come up with an answer let me suggest following questions first:

  • How much views presented to roles differ?

Are you going to hide only couple of buttons and other action elements basically making a page read only for regular users and editable for superusers? If the changes will be small I would probably go with using the same views and only hiding particular elements, probably forging a directive similar to ng-if that would allow enabling/disabling particular functionality declaratively only-role='operator, admin'. On the other hand if views are going to be vastly different then employing different templates can simplify markup greatly.

  • How much actions available on particular page differ depending on role?

Do actions that look similar on surface differ in inner workings for different roles? In example if you have Edit action available both for user and admin role but in one case it starts wizard like UI and in other a complex form for advanced users then having a separate controller makes more sense. On the other hand if admin actions are a superset of user actions then having single controller seems easier to follow. Note that in both cases keeping controller things pays off - they should only glue views to behaviour that is encapsulated in services/view models/models/pick a name

  • Will you have many contextually separate links leading to particular page from different places of the app?

For instance being able to provide navigation to particular page by simply writing ui-sref="dashboard" regardless of the current user role may be beneficial if it exists in various contexts. If that's the case then having them defined under single route/state seems more maintainable then a conditional logic used to build different ui-sref/ng-href based on role. However you could also define routes/states dynamically based on user role - loaded dynamically or not

  • Will views and actions available to different roles on particular page evolve separately or together?

Sometimes we first build features for regular users then for premium and then for ultimate. It's not unusual to divide work on pages for user and admin between team members especially if clear boundaries can be drawn easily. In such case having separate views and controllers can simply developers work avoiding conflicts. Of course it's not all rainbows and unicorns - team must be very disciplined to remove duplication that most likely will happen.

Hope that my suggestions will help you decide.