Adding Config to your AngularJS app
For the past few weeks, I've been building a Web App based on AngularJS.
I wanted it to act differently for different configurations, and I wanted to store the configuration in a simple Config file (sounds like standard procedure),
but for some odd reason, I couldn't find any example or common way to do such a thing, so I improvised.
I simply wrote a new config.js file (where my app.js is, starting with Angular seed), and inside added a new config module.
config.js
|
|
Then I added the newly created myApp.config module into my myApp.controllers module (inside controllers.js), as well as added the individual constants I want to have available inside each controller (sadly that was a must).
controllers.js
|
|
At which point, if I want to, for instance get APP_NAME within the View,
I just add it to the scope in the controller:
controllers.js
|
|
This seems to be an awful lot of trouble, I didn't want to write .constant over and over again, so, I separated the data from the constant definition:
config.js
|
|
This definitely makes it easier to change settings, plus it just looks better.
I still didn't like the fact that I had to name all the variables I wanted from the config in advance,
so I simply packed them in an Object (Objects are defined with {}, and Arrays with []):
config.js
|
|
controllers.js
|
|
That's definitely more elegant, plus now I can divide my config into different sections and
only import the ones I need for each individual Controller.
I'd be happy to hear some other options to do this,
though I'm pretty satisfied with this solution.