使用外部json文件的Stateprovider配置

时间:2015-12-03 16:04:39

标签: javascript angularjs json

我正在使用angular.js和$stateProvider。我想使用states.json之类的东西来管理所有状态,而不是逐个写它们,就像我现在正在做的那样:

function configState($stateProvider, $urlRouterProvider, $compileProvider) {

    function resolveUrl(path){
        var loadUrl = { 
            loadModule: ['$ocLazyLoad', function($ocLazyLoad) {               
                return $ocLazyLoad.load(path);
            }]
        };
        return loadUrl;
    }

    $compileProvider.debugInfoEnabled(true);

    // Set default state
    $urlRouterProvider.otherwise("/dashboard");
    $stateProvider

    // Dashboard - Main page
    .state('dashboard', {
        url: "/dashboard",
        templateUrl: "views/dashboard.html",
        data: {
            pageTitle: 'Dashboard',
        }
    })
    .state('reports', {
        url: "/reports",
        templateUrl: "views/reports.html",
        data: {
            pageTitle: 'Reports',
        }
    })
    .state('invoices', {
      url: "/invoices",
      controller: 'invoicesCtrl',
      templateUrl: '/invoices/views/invoices.html',
      resolve: resolveUrl('/invoices/app/js/compiled/invoices_app.js')
    })
    .state('invoices.upload', {
        url: "/upload",
        controller: 'invoicesCtrl',
        templateUrl: '/invoices/views/invoices.html',
        resolve: resolveUrl('/invoices/app/js/compiled/invoices_app.js')
    })
    .state('users', {
        url: "/users",
        controller: 'usersCtrl',
        templateUrl: '/users/views/users.html',
        resolve: resolveUrl('/users/app/js/compiled/users_app.js')
    });
}

angular
    .module('homer')
    .config(configState)
    .run(function($rootScope, $state) {
        $rootScope.$state = $state;
    });

这可能吗?

1 个答案:

答案 0 :(得分:0)

假设your.json文件遵循以下结构:

{
    "invoices": {
        "name": "invoices",
        "url": "/invoices",
        "controller": "invoicesCtrl",
        "templateUrl": "./invoices.html"
    },
    "reports": {
        "name": "reports",
        "url": "/reports",
        "controller": "reportsCtrl",
        "templateUrl": "./reports.html"
    },
}

在.config方法参数函数

中的for in循环中循环遍历它们
for(var prop in states){
    $stateProvider.state(prop, states[prop])
}

PS:我认为你不能在json对象中嵌入像resolveUrl这样的js函数