how to define constants for Angular JS in a different file
As such you are using AngularJS, you can use Constant Service. as a constant can be injected anywhere including configuration calls in angularjs application.
Also, as the name suggests, the constants are fixed, they get applied before other provide methods. See $provide.constant() for more detail.
// Storing a single constant valuevar app = angular.module('myApp', []);app.constant('appName', 'My App');// Now we inject our constant value into a test controllerapp.controller('TestCtrl', ['appName', function TestCtrl(appName) { console.log(appName);}]);// Storing multiple constant values inside of an object// Note: values in the object mean they can be modifiedvar app = angular.module('myApp', []);app.constant('config', { appName: 'My App', appVersion: 1.0, apiUrl: 'http://www.facebook.com?api'});// Now we inject our constant value into a test controllerapp.controller('TestCtrl', ['config', function TestCtrl(config) { console.log(config); console.log('App Name', config.appName); console.log('App Name', config.appVersion);}]);
You can use a factory (I personnaly always use storage.factory.js in my projects). Easy to inject everywhere and you can use some functions to setup your constants or change them a little bit if you want.
angular.module('app') .factory('storage', storageFactory); function storageFactory() { const data = { serverAddress : 'http://server.address:port' }; return data; }
file 1:
(function () { 'use strict'; angular.module('app', [ 'app.constants' ]).value('CONSTANT_EXAMPLE', 'value example') .value('OTHER_EXAMPLE', 'other example');})();
file 2:
(function () { 'use strict'; angular.module('app.example-use', []) .factory('example', example); example.$inject = ['CONSTANT_EXAMPLE']; // and others injections function example(CONSTANT_EXAMPLE) { // and others injections function getConstantExample() { var option = CONSTANT_EXAMPLE; // use ... } return { getConstantExample: getConstantExample }; }})();