Asik
Asik

Reputation: 7977

AngularJS : UI-router setting configurations using directives

I understand the configuration settings for UI-router and it is working fine. Now I am trying to move the following configuration to directives. So that, the length of code will be reduced in js file. May be, it is poor design but I want to achieve this :)

Current Configuration (As per UI-router design)

//Router Configuration
angular.module('myApp', ['ui.router']).config(function($stateProvider) {
  $stateProvider.state('addCustomer', {
    url: "/addCustomer",
    templateUrl: 'views/customer/add_customer.html',
    controller: 'addCustomerController'
  });

  ...No of configuration, list is very big...
});  

//In Template
<a ui-sref="addCustomer">Add Customer</a>

What I am trying to change

//Router Configuration
angular.module('myApp', ['ui.router']).config(function($stateProvider) {

});  

//In Template
<a ui-sref="addCustomer" router-info="{'url':'/addCustomer', 'templateUrl':'views/customer/add_customer.html', 'controller':'addCustomerController'}">Add Customer</a>

//Directive- Dynamic routing
angular.module('myApp').directive('routerInfo', function(){
    var directive = {};
    directive.restrict = 'A';

    directive.compile = function(element, attributes) {

        var linkFunction = function($scope, element, attributes) {
            //Here I understand, I can not inject stateprovider. So kindly suggest any other way to do this
            //$stateProvider.state(attributes.uiSref, attributes.routerInfo);
        }

        return linkFunction;
    }

    return directive;
});

How to add UI-router configuration from directives? Is there any API available to set? or any other better way to handle this... My intention is to reduce code in config block.

Upvotes: 0

Views: 736

Answers (1)

m59
m59

Reputation: 43745

If you're trying to avoid having one giant config block, simply use multiple config blocks and put each one in its own file. There's no reason not to put configuration code in a config block, it just sounds like you need to approach it a better way, so split it up into smaller blocks.

Example:

// config/routes/user.routes.js

angular.module('yourModule')
.config([
  '$stateProvider',
  function($stateProvider) {

    $stateProvider
    .state('user', {
      url: '/users/:userName',
      abstract: true,
      // etc
    })
    .state('user.main', {
      url: '',
      //etc
    })
    .state('user.stuff', {
      url: '/stuff',
      // etc
    })
    ;

  }
])
;

And repeat for each set of routes:

// config/routes/more.routes.js

angular.module('yourModule')
.config([
  '$stateProvider',
  function($stateProvider) {

    $stateProvider
    .state('more', {
      url: '/more-routes',
      //etc
    })
    ;

  }
])
;

Upvotes: 1

Related Questions