使用ui-router从localStorage动态加载状态到视图中

时间:2016-05-05 12:44:38

标签: angularjs angular-ui-router

Hello在我的应用程序中,当用户登录他们的数据时,从服务器返回他们的数据以及他们分配的角色,并且每个分配的角色都是一个菜单数组。这是成功登录后返回的数组的示例:

{
  "user": {
    "id": 1,
    "username": "xxx",
    "email_address": "xxx@yahoo.com",
    "roles": [
      {
        "id": 1,
        "name": "Administrator",
        "description": "Administrator Role",
        "slug": "administrator",
        "menus": [
          {
            "id": 1,
            "parent_id": 0,
            "name": "Users",
            "icon": "fa-users",
            "description": "Users Menu Group",
            "route": "main.users.view"
          },
          {
            "id": 2,
            "parent_id": 1,
            "name": "New",
            "icon": "fa-plus",
            "description": "New User",
            "route": "main.users.new"
          },
          {
            "id": 3,
            "parent_id": 1,
            "name": "View",
            "icon": "fa-th-list",
            "description": "View All Users",
            "route": "main.users.view"
          },
          {
            "id": 4,
            "parent_id": 1,
            "name": "Edit",
            "icon": "fa-pencil",
            "description": "Edit User",
            "route": "main.users.edit"
          },
          {
            "id": 5,
            "parent_id": 1,
            "name": "Delete",
            "icon": "fa-trash-o",
            "description": "Delete User",
            "route": "main.users.delete"
          },
          {
            "id": 10,
            "parent_id": 0,
            "name": "Roles",
            "icon": "fa-user-secret",
            "description": "Roles Menu Group",
            "route": "main.users.roles"
          },
          {
            "id": 11,
            "parent_id": 6,
            "name": "New",
            "icon": "fa-plus",
            "description": "New Role",
            "route": "main.roles.new"
          },
          {
            "id": 12,
            "parent_id": 6,
            "name": "View",
            "icon": "fa-th-list",
            "description": "View All Roles",
            "route": "main.roles.view"
          },
          {
            "id": 13,
            "parent_id": 6,
            "name": "Edit",
            "icon": "fa-pencil",
            "description": "Edit Roles",
            "route": "main.roles.edit"
          },
          {
            "id": 14,
            "parent_id": 6,
            "name": "Delete",
            "icon": "fa-trash-o",
            "description": "Delete Roles",
            "route": "main.roles.delete"
          }
        ]
      },
      {
        "id": 2,
        "name": "Manager",
        "description": "Manager Role",
        "slug": "manager",
        "menus": []
      }
    ]
  },
  "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vcGVzbGVhcm4uZGV2L2FwaS9sb2dpbiIsImlhdCI6MTQ2MjQ0NzY0MiwiZXhwIjoxNDYyNDUxMjQyLCJuYmYiOjE0NjI0NDc2NDIsImp0aSI6IjA1NGU1NzY2ZWM3ODBhZDJhNDY3YWY4MWFjZjI1Y2RkIiwic3ViIjoxfQ.WGr2wOMdS3ipcIXw0906o2hD_apIIM0aYmgDiu8Kiqw",
  "status_code": "200"
}

现在我有一个NavCtrl来处理从本地存储中提取和解析每个角色的菜单:

angular.module('app.ctrls')
    .controller('NavCtrl', NavCtrl);

    // Injecting Dependencies
    NavCtrl.$inject = ['$state', '$rootScope', '$auth', '$localStorage'];

    // Controller Function
    function NavCtrl($state, $rootScope, $auth, $localStorage) {
        var vm = this;

        // Setting Variables and Properties
        vm.user = {};
        vm.roles = [];
        vm.menus = [];

        vm.scrollConfig = {
            autoHideScrollbar: true,
            theme: 'light',
            advanced: {
                updateOnContentResize: true
            },
            scrollInertia: 0
        };

        vm.topLevelFilter = function(item) {
            return item.parent_id == 0;
        };

        /* Controller Initialiser */
        vm.init = function() {
            // Fetching menus from local storage
            vm.user = $localStorage.getObject("user");
            vm.roles = vm.user.roles;
            vm.menus = vm.roles[0].menus;
        }

        /* initialising Controller */
        vm.init();

    }

我现在遇到的麻烦是当我尝试将每个ui-sref中的值“放”在ng-repeat中时,如下所示:

<div snap-drawer class="side-bar-container" ng-controller="NavCtrl as nav">

    <div class="side-bar">
        <div class="header">
            <img src="//:0" ng-src="images/logo.png" title="Xxx" alt="Xxx" class="logo" />
        </div>

        <div ng-slimscroll size="3px" opacity="0.3" class="ng-slimscroll">
            <div class="list-group">

                <a ui-sref="main.dashboard" ui-sref-active="active"  class="list-group-item">
                    <i class="fa fa-home icon pull-left"></i>
                    <span class="title col-xs-7">Dashboard</span>
                    <i class="fa fa-chevron-right margin-top-5 pull-right"></i>
                </a>

                <!-- Looping through menus array with ng-repeat directive -->
                <a ui-sref="main.users.roles" ui-sref-active="active" class="list-group-item" ng-repeat="item in nav.menus | filter: nav.topLevelFilter track by $index">
                    <i class="fa {{ item.icon }} icon pull-left"></i>
                    <span class="title col-xs-7 ">{{ item.name }}</span>
                    <i class="fa fa-chevron-right margin-top-5 pull-right"></i>
                </a>

            </div>
        </div>

    </div>

</div>

当我尝试在刷新浏览器后点击链接时,我在浏览器控制台中收到以下错误:

  

错误:无法从状态'main'

解析'main.users.roles'

这是我的路线档案:

angular.module('app.routes', [])
    .config(['$stateProvider', '$locationProvider', '$urlRouterProvider', '$authProvider', function($stateProvider, $locationProvider, $urlRouterProvider, $authProvider) {
        $stateProvider
            .state('auth', {
                abstract: true
            })
            .state('auth.login', {
                url: '/login',
                views: {
                    'main@': {
                        templateUrl: 'tpls/login.html',
                        controller: 'AuthCtrl',
                        controllerAs: 'vm'
                    }
                },
                data: {
                    cssClasses: 'login'
                }
            })
            .state('auth.reset', {
                url: '/password-reset',
                views: {
                    'main@': {
                        templateUrl: 'tpls/reset.html',
                        controller: 'AuthCtrl',
                        controllerAs: 'vm'
                    }
                },
                data: {
                    cssClasses: 'reset'
                }
            })

            .state('main', {
                abstract: true,
                views: {
                    'main@': {
                        templateUrl: 'tpls/main.html'
                    }
                }
            })
            .state('main.dashboard', {
                url: '/dashboard',
                views: {
                    'content@main': {
                        templateUrl: 'tpls/dashboard.html',
                        controller: 'DashBoardCtrl',
                        controllerAs: 'vm'
                    }
                }
            })

            .state('main.users', {
                abstract: true,
                url: '/users'
            })
            .state('main.users.roles', {
                url: '/roles',
                views: {
                    'content@main': {
                        templateUrl: 'tpls/roles.html',
                        controller: 'RolesCtrl',
                        controllerAs: 'vm'
                    }
                }
            });

        $urlRouterProvider.otherwise("/login");
        // Satellizer configuration that specifies which API
        // route the JWT should be retrieved from
        $authProvider.loginUrl = '/api/login';

        $locationProvider.html5Mode({
            enabled: true,
            requireBase: false
        });
    }]);

当点击时,菜单会根据当前角色(从分配给该特定用户的角色列表中选择)进行更改。

1 个答案:

答案 0 :(得分:0)

显然,这只是其中一个无法解释的事情,经过几十次运行之后终于奏效了。所以看来我的实施没有任何问题。