AngularJS - Getting Module constants from a controller

Solution 1:

I don't think it is valid to use the module name in an injection like that. You can simply inject the constants by name, though:

angular.module('myApp.controllers', ['myApp.config'])
  .controller('ListCtrl', ['$scope', 'APP_NAME', function($scope, appName) {
     $scope.printme = appName;
}]);

Solution 2:

I think the simplest approach is to add a constant using an object literal. This fits most application configuration use cases I think, because it supports a complex config object. The constant step also runs early, before other providers are registered.

angular.module('myApp').constant('cfg', {
  url: 'https://myapi.com/v1/',
  httpTimeout: 5000
})

To use it you just inject cfg:

angular.module('myApp').factory('user', function(cfg, $http){
  // cfg and $http together at last
})

Solution 3:

It should also be noted that SimplGy's solution means that the 'cfg' object is a constant, however the properties of that object are not. This means, that you cannot reassign 'cfg' like so:

cfg = { randomProperty: randomValue };

You CAN reassign the properties of the 'cfg' object like so:

cfg.url = 'BrandNewURL.com';
cfg.httpTimeout = 30;

Solution 4:

Check out the use of constants in this example:

angular
.module('abp001App', ['ngRoute'])
.constant("myConfig", {
    "url": "http://localhost",
    "port": "80"
})
.config(function ($routeProvider) {
    $routeProvider
        .when('/', {
            templateUrl: 'views/main.html',
            controller: 'MainCtrl'
        })
        .otherwise({
            redirectTo: '/'
        });
})
.controller('MainCtrl', function (myConfig) {
    // Do something with myConfig...
});