Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including global config in AngularJS module dependencies

I've developed an AngularJS app that uses browserify and injects modules as dependencies into the main app. In all of the modules I want to be able to access global configs from a routingConfig.js file.

Partial code:

main app.js

  var routingConfig = require('./common/config/routingConfig');

  module.exports = angular.module('app', [
    // modules as dependencies
    require('./home/home').name,
    require('./login/login').name
  ]);

module home.js

  var HomeCtrl = require('./homeController');

  module.exports = angular.module('app.home', [
    'home/home.tpl.html',
    'ui.router'
  ])
  .config(function config($stateProvider) {
    $stateProvider
      .state('home', {
        url: '/',
        controller: 'HomeCtrl',
        templateUrl: 'home/home.tpl.html',
        data: {
          pageTitle: 'Home'

          /**
           * I want to be able to use values from routingConfig here...
           */
        }
      });
  })
  .controller('HomeCtrl', ['$scope', HomeCtrl]);

I could of course require routingConfig in every module, and that would work, but ideally I'd like to be able to just require it once and use it globally in the main app and its modules. Any ideas would be much appreciated.

like image 220
jdiver Avatar asked May 17 '26 07:05

jdiver


1 Answers

Solution came into my mind is following.

1) Create new module named as 'app.config' and use angular constant service (https://docs.angularjs.org/api/auto/service/$provide#constant) for registering and using of your config:

 var routingConfig = require('./common/config/routingConfig');

 module.exports = angular.module('app.config', [
 ])
 .constant('routingConfig', routingConfig);

2) Add this 'app.config' module to list of module dependencies in app.js

 module.exports = angular.module('app', [
   // modules as dependencies
   require('./config/routingConfig').name,
   require('./home/home').name,
   require('./login/login').name
 ]);

3) You could now inject routingConfig and use it:

 module.exports = angular.module('app.home', [
   'home/home.tpl.html',
   'ui.router'
 ])
 .config(function config($stateProvider, routingConfig) {

    ... use routingConfig here...
 });
like image 118
Egor Smirnov Avatar answered May 20 '26 17:05

Egor Smirnov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!