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.