How To Set Environmental Variables In AngularJS

In AngularJS, you can set environment variables in the configuration phase of your application, typically in a separate file that holds the configuration information. Here's an example of how you can set environment variables in AngularJS:

Step 1

Create a file, say config.js, in your application's root directory to store the environment variables.

Step 2

Define the environment variables in the file using the following code,

"use strict";
 angular.module('config', [])
.constant('ENV', {name:'development',tokenURL:'http://localhost:62511/token',apiURL:'http://localhost:62511/api',biUrl:'http://localhost:4200/',backgroundimage:'../images/backgroundimage.jpg',logo:'images/ogo.png'});

Step 3

Include the config.js file in your HTML file, just like any other JavaScript file:

<script src="scripts/index.config.js"></script>

Step 4

Inject the env constant in your AngularJS controllers, services, or directives to access the environment variables,

angular.module("myApp").controller("MyController", function($scope, env) {
    console.log(env.apiUrl);
    console.log(env.debugEnabled);
});
development: {
        options: {
            dest: '<%= yeoman.app %>/scripts/config.js'
        },
        constants: {
            ENV: {
                name: 'development',
                tokenURL: "http://localhost:62511/token",
                apiURL: "http://localhost:62511/api",
                biUrl: "http://localhost:4200/",
                backgroundimage: "../images/backgroundimage.jpg",
                logo: "images/logo.png",
            }
        }
    },
    qa: {
        options: {
            dest: '<%= yeoman.dist %>/scripts/config.js'
        },
        constants: {
            ENV: {
                name: 'qa',
                tokenURL: "https://qa.azurewebsites.net/token",
                apiURL: "https://qa.azurewebsites.net/api",
                biUrl: "https://qa-dashboard.azurewebsites.net/",
                backgroundimage: "../images/backgroundimage.jpg",
                logo: "images/logo.png",
            }
        }
    },

Grunt command to run the Application,

grunt build --qa


Similar Articles