AngularJS - 动态$ StateProvider

时间:2014-06-03 00:13:08

标签: angularjs angular-ui-router

我急切地想要创建一个dyanmic $ StateProvider:

标准静态$ StateProvider:

    $stateProvider
      .state('main',
      {
        url: '/',
        templateUrl: '/views/main.html',
        controller: 'MainCtrl'
      })
      .state('login',
      {
        templateUrl: '/views/login-form.html',
        controller: 'LoginCtrl'
      })
      .state('logout',
      {
        controller: 'LogoutCtrl'
      })
      .state('sales', {
        templateUrl: '/views/sales-data.html',
        controller: 'SalesDataCtrl',
        resolve: {
          user: 'User',
          authenticationRequired: function(user) {
            user.isAuthenticated();
          }
        }
      });

动态$ StateProvider:

var verify = function(user) { user.isAuthenticated(); };

var states= [
{ name: 'main', url: '/', templateUrl: '/views/main.html', controller: 'MainCtrl' },
{ name: 'login', url: '', templateUrl: '/views/login-form.html', controller: 'LoginCtrl' },
{ name: 'logout', url: '', templateUrl: '', controller: 'LogoutCtrl' },
    {
        name: 'sales',
        url: '',
        templateUrl: '/views/sales-data.html',
        controller: 'SalesDataCtrl',
        //resolve:
        //[
        //    { user: 'User', authenticationRequired: 'verify();' }
        //]
    }
];
       // w/o the array brackets in resolve the navigation does not work.
       // with the array brackets, once sales is clicked I get:
       // Error: [ng:areq] Argument 'fn' is not a function, got Object

只要我没有使用解决方法,以下两种方法就可以使用

  This works:
   angular.forEach(states, function(state) {
        $stateProvider.state(state);
    });

   This works:
   angular.forEach(states, function(state) {
        $stateProvider.state(state.name, state);
    });

问题:如何使这个动态$ StateProvider与解析一起使用?

2 个答案:

答案 0 :(得分:2)

<强>解决方案:

var states = [
{ name: 'main', url: '/', templateUrl: '/views/main.html', controller: 'MainCtrl' },
{ name: 'login', url: '', templateUrl: '/views/login-form.html', controller: 'LoginCtrl' },
{ name: 'logout', url: '', templateUrl: '', controller: 'LogoutCtrl' },
    {
        name: 'sales',
        url: '',
        templateUrl: '/views/sales-data.html',
        controller: 'SalesDataCtrl',
        resolve: {
            user: 'User',
            authenticationRequired:
            ['user', function(user) { user.isAuthenticated(); }] // <-------------------------
        }
    }
];

    angular.forEach(states, function (state) {
        $stateProvider.state(state.name, state);
    });

答案 1 :(得分:0)

我认为你错误地调用$stateProvider.state(...),它需要一个状态ID,然后是配置对象。

假设您的name属性有效且唯一,您应该能够执行此操作(或根据需要进行调整):

angular.forEach(states, function(state) {
    $stateProvider.state(state.name, state);
});