简体   繁体   中英

Angular + ui-angular dynamic tabs with dynamic controllers

I need to construct permission based admin dashboard. Header of html consists of some main havs and the last nav is for Settings . I use angular-ui-router for states. and when user goes to the Settings link I need to upload from server tabs that user has access to.

My state provider

 $stateProvider
    .state('home', {
        url: "/",
        templateUrl: "templates/home/index.html"
    })
    .state('settings', {
        url: "/settings",
        controller: "SettingsController",
        templateUrl: "templates/home/settings.html",
    })
    .state('settings.users', {
        url: "/users",
        controller: "SettingsUsersController",
        templateUrl: "templates/home/settings/users.html",
    })
    .state('settings.roles', {
        url: "/roles",
        controller: "SettingsRolesController",
        templateUrl: "templates/home/settings/roles.html",
    });

SettingsController looks like this:

app.controller('SettingsController', ['$scope', '$http',
    function($scope, $http) {
        $scope.tabs = [];

        $http({
            method: 'GET',
            url: '/api/menu/get'
        }).
        success(function(data, status, headers, config) {
            $scope.tabs = data;
        }).
        error(function(data, status, headers, config) {
            window.location = '/auth/login';
        });
    }
]);

Sample server answer

[{
    "url": "settings.users",
    "title": "Users"
}, {
    "url": "settings.roles",
    "title": "Roles"
}]

My settings.html

<div class="container">
  <ul class="nav nav-tabs nav-justified">
    <li ng-repeat="tab in tabs" ng-class="{active: $first}">
      <a href="{{tab.url}}">{{tab.title}}</a>
    </li>
  </ul>
</div>

How to load first tab on $http end in SettingsController , also to connect it to corresponding Controller? And how to switch active tab on different states?

Don't know if it is possible to define routes dynamically, but you could achieve your targets the following way.

  1. Define all possible routes of your app.
  2. Make them inaccessible for user without certain permissions (i use this approach ).
  3. Load user's permissions.
  4. Build tabs from those permissions (don't show nav before this point).

Additionally, it's worth checking on server side if user has permissions to page when he tries to load it. Because he can look at code and to try to access it bypassing the navigation.

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