Is there a way in AngularJS to define constants with other constants?

raulricardo21 picture raulricardo21 · Aug 28, 2013 · Viewed 93k times · Source

I'm trying to define constants with other constants, but it seems that it can't be done, because the initial constant isn't ready when the required constant depending require it. I want to be sure if this isn't possible at all.

Currently I have constants in this way:

angular.module('mainApp.config', [])
    .constant('RESOURCE_USERS_DOMAIN', 'http://127.0.0.1:8008')
    .constant('RESOURCE_USERS_API', 'http://127.0.0.1:8008/users')
    // Specific routes for API
    .constant('API_BASIC_INFORMATION', RESOURCE_USERS_API + '/api/info')
    .constant('API_SOCIAL_NETWORKS', RESOURCE_USERS_API + '/api/social')
    ;

The second two constants are what I want to accomplish.

Answer

Linkmichiel picture Linkmichiel · Oct 24, 2014

An easy way to do this is like this:

var myApp = angular.module("exampleApp",[]);

myApp.constant('RESOURCES', (function() {
  // Define your variable
  var resource = 'http://127.0.0.1:8008';
  // Use the variable in your constants
  return {
    USERS_DOMAIN: resource,
    USERS_API: resource + '/users',
    BASIC_INFO: resource + '/api/info'
  }
})());

And use the constants like this:

myApp.controller("ExampleCtrl", function(RESOURCES){
  $scope.domain = RESOURCES.USERS_DOMAIN;
});

Credits: link