where do I put configs in a angularjs app?

98 views Asked by At

In my angular app, I have a URL to which I connect for retrieving some data, a CORS enabled server.

Now, so far I had it hardcoded in my javascript file:

server_url = "http://localhost:7888/api.php/json?id=2"

Now, on test and production, those URLs of course are not valid...and everytime I do a git pull it overrides my customizations.

Where would I elegantly put a config like that in an angular app?

2

There are 2 answers

0
pedrommuller On

well, basically I'd adopt a mean.js approach here, it's quite easy to implement and it could be useful to you or anybody else.

you have to write from your middleware into your main HTML file in angular (ex: index.html), in your case the URL for your endpoint have to change depending on your environment just to keep it simple let's say we have dev (localhost) and production (mydomain.com)

in your index html do a simple write:

 <script type="text/javascript">
        <?php 
         if(strpos( $_SERVER['HTTP_HOST'], 'mydomain.com') !== false){
             print "var endpoint = '"+ $server_url+ "';" 
         } else{
            print "var endpoint = '"+ $local_url+ "';" 
         }

         ?>
    </script>

one you got that into your main index.html it's available in angular by using the window object, so you can wrap it into a constant or a service.

this is the example for a constant:

angular.module('app').run(function () {

}).value('endpoint', window.endpoint);

I'm not fluent in PHP, but I hope you can get my point

5
The Head Rush On

Declare it as a constant. Assuming you have an app named App:

angular.module('App', []).constant("urls", {"server_url":"http://localhost:7888/api.php/json?id=2"});

Once declared as a constant, you'd inject it as a dependency, just as you would a service.