Passing configuration to Angular

This is something that we got wrong on our project initially, then had a guy named Mark come on board and nail a very clean solution.

What we were trying to accomplish: we wanted to give our Angular Singe Page App some configuration data for initialization. Things like a CSRF token and API URL, so not necessarily things we could load from a web service.

The wrong way to do it:

We started off using an ng-init on our element. If you RTFM on ng-init they make it very clear that you should not be using it for that purpose. In our defense, the name “init” is right there in the name and the warning wasn’t as bright red in earlier versions of the documentation.

A better way to do it:

What we are doing now is putting this in our server-side template:

<script>
angular.module('ns-config', [])
    .constant('config', {{config|js}});
</script>

and then inject the ns-config module into our project. By using Angular’s constant() instead of value() the config object is available in our application’s .config() block.

Leave a Reply

To respond on your own website, enter the URL of your response which should contain a link to this post's permalink URL. Your response will then appear (possibly after moderation) on this page. Want to update or remove your response? Update or delete your post and re-enter your post's URL again. (Learn More)