StackOverflow_23429055: angularjs-ui-router-load-template-and-controller-based-on-user-role

Illustration of answer to http://stackoverflow.com/questions/23429055/angularjs-ui-router-load-template-and-controller-based-on-user-role.

by ExpertSystem

HTML

<script src="http://code.angularjs.org/1.2.23/angular.min.js"></script>
<script src="http://code.angularjs.org/1.2.23/angular-route.min.js"></script>
<div ng-controller="mainCtrl">
    <div class="text-right" ng-show="isLoggedIn()">
        <button ng-click="logout()">Logout</button>
        <hr />
    </div>
    <div ng-view></div>
</div>

<!-- Templates -->
<script type="text/ng-template" id="views/login.html">
    <h1>User login</h1>
    <button ng-click="loginAs(role)" ng-repeat="role in roles">
        Login as {{role}}
    </button>
</script>
<script type="text/ng-template" id="views/user/dashboard.html">
    <div ng-controller="userDashboardCtrl">
        <h1>Hello, user !</h1>
        Available actions:
        <ul><li ng-repeat="action in actions">{{action}}</li></ul>
    </div>
</script>
<script type="text/ng-template" id="views/admin/dashboard.html">
    <div ng-controller="adminDashboardCtrl">
        <h1>Hello, admin !</h1>
        Available actions:
        <ul><li ng-repeat="action in actions">{{action}}</li></ul>
    </div>
</script>

<!-- -=-=-=-=- -=[IGNORE BELOW THIS LINE]=- -=-=-=-=- -->
<!-- Page Footer -->
<small class="footer" ng-controller="footerCtrl">
    <b>Angular v{{version.full}}</b> ({{version.codeName}})
    <span class="right">
        &copy; <a ng-href="{{authorUrl}}" target="_blank">ExpertSystem</a>
    </span>
</small>

CSS

.text-right {
    text-align: right;
}

/* -=-=-=-=- -=[IGNORE BELOW THIS LINE]=- -=-=-=-=- */
/* Page Footer */
body { padding-bottom: 22px; }
.footer { background-color: White; border-top: 1px solid rgba(100, 100, 100, 0.33); bottom: 0; display: block; font-size: 0.75em; height: 20px; left: 0; margin: 0 5px; overflow: auto; padding: 5px; position: fixed; right: 0; }
.right { float: right; }

JavaScript

var app = angular.module('myApp', ['ngRoute']);
app.controller('mainCtrl', function ($location, $scope, User) {
    $scope.isLoggedIn = function () {
        return User.isLoggedIn();
    };
    $scope.logout = function () {
        User.logout();
        $location.path('/login');
    };
});
app.controller('loginCtrl', function ($location, $scope, User) {
    $scope.roles = ['user', 'admin'];
    $scope.loginAs = function (role) {
        User.setRole(role);
        $location.path('/dashboard');
    };
});
app.controller('adminDashboardCtrl', function ($scope) {
    $scope.actions = ['Create', 'Read', 'Update', 'Delete'];
});
app.controller('userDashboardCtrl', function ($scope) {
    $scope.actions = ['Read', 'Update'];
});

app.service('User', function ($http, $templateCache) {
    var guestRole = 'guest';
    var facadeUrl = 'views/dashboard.html';
    var emptyTmpl = '';
    var errorTmpl = 'Failed to load template !';
    var tempTmpl  = 'Loading template...';

    this.isLoggedIn = function () {
        return this.role !== guestRole;
    };

    this.logout = function () {
        this.role = guestRole;
        $templateCache.put(facadeUrl, tempTmpl);
    };

    this.setRole = function (role) {
        this.role = role;

        var url = 'views/' + role + '/dashboard.html';        
        $templateCache.put(facadeUrl, emptyTmpl);
        $http.get(url, {cache: $templateCache}).
              success(function (tmpl) {
                  $templateCache.put(facadeUrl, tmpl);
              }).
              error(function () {
                  $templateCache.put(facadeUrl, errorTmpl);
              });
    };
    
    this.logout();
});

app.config(function ($routeProvider) {
    $routeProvider.
        when('/dashboard', {
            templateUrl: 'views/dashboard.html'
        }).
        when('/login', {
            templateUrl: 'views/login.html',
            controller:  'loginCtrl'
        }).
        otherwise({
            redirectTo: '/login'
     ...