Alan Alan - 3 months ago 47
AngularJS Question

How can I split my route configuration into multiple files with angular-ui-router?

Presently I have the one file like this:

app.config([
'$locationProvider',
'$sceDelegateProvider',
'$sceProvider',
'$stateProvider',
($locationProvider,
$sceDelegateProvider,
$sceProvider,
$stateProvider) => {

$locationProvider.html5Mode(true);
$sceProvider.enabled(false);

var home = {
name: 'home',
//template: '<div data-ui-view></div>',
url: '/home/'
};

var homeAccess = {
name: 'home.access',
url: 'access',
views: {
'home@': {
templateUrl: 'app/access/partials/webapi.html'
}
},
onExit: ['accessService', (acs: IAccessService) => {
acs.clear();
}]
};



$stateProvider
.state(homeAccess)
.state(home);
}])


The problem is that I have so many states it's now grown to over 1,200 lines.

Is it possible to split the app.config into multiple files and if so how can I do this?

Answer

You can take a look at this to know how to structure your code in Angular Best Practices Directory Structure. You can create different files with your states, and separate them in each feature folder. If you don't want to separate them by folder, just drop them in separate files. In each file you just have to export the function that you register as a config.

This is the home route (home-route.js):

function stateConfig ($locationProvider, $sceDelegateProvider, $sceProvider, $stateProvider) {
        $locationProvider.html5Mode(true);
        $sceProvider.enabled(false);

        var home = {
            name: 'home',
            template: 'Home',
            url: '/home'
        };



    $stateProvider
        .state(home);
}

module.exports = stateConfig;

This will be the access route (home-access-route.js):

    function stateConfig ($locationProvider, $sceDelegateProvider, $sceProvider, $stateProvider) {
        $locationProvider.html5Mode(true);
        $sceProvider.enabled(false);

        var homeAccess = {
            name: 'home.access',
            url: '/access',
            template: 'Access',
            parent: 'home'
        };



    $stateProvider
        .state(homeAccess)
}

module.exports = stateConfig;

And then in your index.js file of your module/app you are going to do something like:

var TestsRoute  = require('./home-route.js');
var HomeAccessRoute  = require('./home-access-route.js');

var app = angular.module('HomeAccess', []);

app.config(['$locationProvider', '$sceDelegateProvider', '$sceProvider', '$stateProvider', HomeRoute]);    
app.config(['$locationProvider', '$sceDelegateProvider', '$sceProvider', '$stateProvider', HomeAccessRoute]);

module.exports = app.name

So in the place where you initialize your application you are just going to have all the separate modules that you've created and register them as dependencies for your app