Angular.js Directive-As-A-Service

Monday February 03, 2014.

In the last six months I have worked on a few large scale products built with Angular.js. I thought I’d share a methodology I have been getting a lot of mileage out of, which I’m calling directive-as-service.

The usual premise is I’ll be working away on a UI and have a need for a components that are related to the part of the interface I am working on, but kind of not really owned by it, and not necessarily a child of it. Things like modals, context menu, progress indicators etc.

To add a twist to the problem, I may not have direct access to the page layout html and I prefer to inject markup like this into the document root to avoid css selector pollution.
I solve this by creating a service which compiles a directive on demand. This makes my directive available via angular’s dependancy injection, and the injection of the directive into the document can also be nicely abstracted by the service.

You’ll notice the service below generates a new root scope, and passes parameters to the directive. I find this makes usage a bit simpler and more predictable than inheriting scope, though it’s easy to inherit the scope using this approach as well, just pass the $scope from your controller to the service instead of a params object and don’t bother new’ing up a rootScope.

Using this directive-as-a-service approach, it makes it very easy to module-out these UI components to be shared across projects, reducing implementation work to including the module and injecting the dependancy to your controller.
The only manual consideration at that point is css, but I suppose if youre feeling shameless you could write that into your directive code as well.

An Example

Comments? Questions?

Comments or feedback via appreciated via @linkthief