Wednesday, 22 April 2015

Creating a Configuration Directive in AngularJS

I have been using AngularJS for a while now and for me anyway it’s one of the easiest JavaScript frameworks around for data binding, but I find that there is one key issue with all of these – injecting configuration.

Now I have seen a few ways of doing this either by switching out script files, which can get confusing when the all the scripts get minified, or by writing script out on the page, and I think that just looks messy.  So I said to myself that there must be an nicer way and I came up with a directive to inject any configuration into an AngularJS application.

I wanted a simple directive that I can be used in jQuery as at the time it was going into an a web application that was jQuery based and being moved to AngularJS so I decided to use the following structure:

This structure would enable a directive to be built around the word ‘config’ and also let jQuery pick up on it. The key part to this is the ‘link’ function in the directive, looping through all the attributes and assigning them to an object property.

The link function would have to look at every attribute in the html element which started with the word ‘config’ and add a value, with the given cased config name, to an angular value variable. So config-some-other-number would become someOtherNumber. This is made easy with JavaScript’s object notation.

The resulting directive looks like this:

So with that in place its just a case of creating the app value and injecting it into the directive.  Here is a gist of a simple demo with has this functionality.

Happy coding!