0

I'm currently working on a project using UI Router. My code currently defines states as part of the app config ( example below ) but the code is growing. Is there a good way to modularize this code both for organization and unit testing? For me the best solution would be to define states as an external service.

.state('page', {
    url: '/page/{id}',
    params: {
      id: ['$q', function ($q) {
        // Code
        return defaultValue;
      }],
    },
    templateUrl: 'page.html',
    'controller': 'CatalogDetailsController',
    'controllerAs': 'details',
    resolve: {
      categories: ['$q', function ($q) {
        // Code
        return promise;
      }],
    },
Vestax159
  • 1
  • 1

2 Answers2

0

I would start by defining the objects separately instead of in-line ( do note that this does make the code less readable)

.state('page', {
    url: '/page/{id}',
    params: myparamsObj // defined somewhere else.
    templateUrl: 'page.html',
    'controller': 'CatalogDetailsController',
    'controllerAs': 'details',
    resolve: myResolveObj, // defined somewhere else.

If your app.config is becoming too big , you could use the approach mentioned in [refactor large AngularJS module config into separate files ] question to split your config part.

Community
  • 1
  • 1
Pratik
  • 868
  • 1
  • 9
  • 24
0

My proposal is based on ES6 modules.

Long story short. Each state has a separate folder, for instance contacts/one/edit. In this folder I have the following files:

  • controller.js, controller.spec.js
  • state.js, state.spec.js
  • state.html

state.js holds the state definition object:

import controller from './edit.controller';
import template from './edit.state.html';

// State name is exported so we can use it in the corresponding tests
export const name = 'contacts.one.edit';

export default {
  name,
  url: '/edit',
  template,
  controller,
  controllerAs: 'ctrl'
};

This configuration could be activated in the module's configuration block:

import oneState from './one/one.state';

export function states($stateProvider) {
  'ngInject';

  $stateProvider
    .state({
      parent: 'app',
      name: 'contacts',
      abstract: true,
      url: '/contacts',
      template: '<div ui-view autoscroll="true"></div>'
    })

    .state(oneState)
    .state(oneEditState)
    // etc...
}

Here you will find the complete example https://github.com/lucassus/angular-webpack-seed/tree/ce4e9b91ce9ed47ca74073d754b0cbacff8cb65f/src/app/contacts/one/edit

luacassus
  • 6,540
  • 2
  • 40
  • 58