AngularJS Constants

I’m working with AngularJS for almost a year and I’ve decided to share my experience and get feedback from the community. If you consider that something is wrong or could be improved, just leave a message in this post.


AngularJS offers a provider for constants that despite is not very popular it could save you hours of debugging.

Let’s see an example about how Constants works and will be used.

    .module('app', [])
    .constant("AppConfig", {
        "url": "http://localhost",
        "port": "80"
    .controller('MainCtrl', function (AppConfig) {
        // Do something with AppConfig...

Above the snippet of code is a classic example, you want a config that could be injectable at any part of your application and it works but maybe is not the best use of a constant.

There are better ways to inject a config in your application, probably the best you can do is to create a service and load with $http a JSON file. This is better for many reasons, but probably the most important is that you can update your config file without modifying your code, so if you have the same project in different servers you can have one source code base. That’s better for testing and maintainability.