userMod2 userMod2 - 3 months ago 29
AngularJS Question

Angular - Constant Variable Decided Conditionally

In my Angular app I have defined a constant such as:

var app = angular.module('app', ['ngTagsInput'])
.constant('API', 'https://www.example.com/api/v1')
})();


However I want this API URL to be dependant on a constant I have set above, namely:

var WORKING_ON_ENV = "dev";


So I've tried to implement this using the following - however its not working - is this actually possible with Angular constants?:

.constant('API', function() {
if (WORKING_ON_ENV == "prod") {
return 'https://www.example.com/api/v1'
} else {
return 'https://www.example.com/api/v2'
}
})


Any advice appreciated.

Thanks.

Answer

You can use a ternary:

var app = angular.module('app', ['ngTagsInput'])
   .constant('API', (WORKING_ON_ENV == "prod" ? 'https://www.example.com/api/v1' : 'https://www.example.com/api/v2'))
})();
Comments