简体   繁体   English

AngularJS - 有条件地为路由设置一个控制器

[英]AngularJS - Conditionally set a controller for the route

I'm using the native AngularJS router and was wondering if there is a way to assign a controller to a route conditionally.我正在使用本机 AngularJS 路由器,想知道是否有办法将控制器有条件地分配给路由。 For example, let's say I have three user types:例如,假设我有三种用户类型:

  • Guest客人
  • User用户
  • System Admin系统管理员

When they come to the home page, I want to be able assign a different controller based on the user type.当他们进入主页时,我希望能够根据用户类型分配不同的控制器。 So I would have three registered controllers: guestHomeCtrl , userHomeCtrl , systemAdminHomeCtrl .所以我会有三个注册的控制器: guestHomeCtrluserHomeCtrlsystemAdminHomeCtrl

I imagined something like this:我想象了这样的事情:

$routeProvider
    .when( '/' , {
        controller: getHomeCtrl(),
        controllerAs: 'homeCtrl'
    })

I know I can just pass in the string of the registered controller, but the main issue is being able to find out what type of user is logged in. I have a userService that typically keeps track of that, but it doesn't seem like I can access it from where I set up the routes.我知道我可以只传递注册控制器的字符串,但主要问题是能够找出登录的用户类型。我有一个userService通常会跟踪它,但它似乎不像我可以从我设置路由的地方访问它。 Or am I mistaken?还是我错了?

Any direction would help out a lot.任何方向都会有很大帮助。

I would suggest using userService with a single controller.我建议将userService与单个控制器一起使用。 Read through the page below, specifically the resolve argument.通读下面的页面,特别是resolve参数。

https://docs.angularjs.org/api/ngRoute/provider/ $routeProvider https://docs.angularjs.org/api/ngRoute/provider/ $routeProvider

This blog post also describes how to use the resolve.这篇博文还介绍了如何使用解析。

http://odetocode.com/blogs/scott/archive/2014/05/20/using-resolve-in-angularjs-routes.aspx http://odetocode.com/blogs/scott/archive/2014/05/20/using-resolve-in-angularjs-routes.aspx

Try sending the specific function or variable you need to the controller.尝试将您需要的特定函数或变量发送到控制器。 I used userService.User.userAccountStatus , but it really depends on the setup in your service file.我使用了userService.User.userAccountStatus ,但这实际上取决于您的服务文件中的设置。

$routeProvider
    .when( '/' , {
        controller: HomeCtrl,
        controllerAs: 'HomeCtrl',
        resolve: { 
          userService: function(userService) {
            return userService.User.userAccountStatus();
          }
        }
    })

I use ngInject for injecting dependencies, but I assume you get the gist of giving services to a controller.我使用 ngInject 来注入依赖项,但我假设您已经掌握了向控制器提供服务的要点。

angular
  .module('app')
  .controller('HomeCtrl', HomeCtrl)

  /** @ngInject */
  function HomeCtrl($scope, $log, $state, userService) {
  }

I can provide further examples if you need them.如果您需要,我可以提供更多示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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