Inject a config in AngularJS

angularjs

Solution

Creating a stand-alone module that only has a service or a directive (or both) is a great way to make application-independent angular code. If you do this you can easily just take that .js file and plop it into any project, and all you need to do is inject it into your applications and it just works.

So doing something like:

angular.module('config', [])
    .factory('config', function() {
        return {
            theme : 'nighttime',
            cursor : 'sword',
            ...
        };
    });

Then you can just inject it into any application like so:

angular.module('myModule', ['config'])
    .factory('myservice', function (config) {
        var theme = config.theme;
        var cursor = config.cursor;
        // do stuff with night-time swords!
    });

This is actually how the angular-ui team package all their directives, each directive is contained within its own module, which makes it easy for others to just take that code and reuse it in all their apps.

Problem

I have a config that I'd like to be able to inject into Angular services, directives, etc. What is the best way to go about doing this? I was playing with the idea of making config module: ``` 'use strict'; angular.module('config', []) ``` But I wasn't sure how to construct the object literal that would be the actual config object that gets injected: ``` angular.module('myModule', ['ngResource', 'config']) .factory('myservice', function ($resource) { return $resource(config.myservice,{}, { // whatever }) }); ``` Would it be okay to just expose config as a service and inject that?

Original source

Related problems