Refactor your Formly forms into a Formly service

Reduce controller bloat and improve the reusability of your Formly forms by creating a Formly service.


If you are a fan of JavaScript, then you probably look for opportunities to refactor as much of your code into JS as you can. The Angular-Formly project is a great example of this: take your HTML forms, and transfer their composition to your JavaScript.

While Formly removes a great deal of bloat from your HTML templates, I found that as your form grows, that bloat get’s transferred to your controller, which crowds your business logic and makes things less reasonable.

The answer to bloated controllers is refactoring into services; which turns out to be a great idea for Formly: modularity, readability, and reusability.

Here’s how to easily refactor your Formly forms into a service from an existing controller:

Step 1: Create your formly.forms.service.js file

Here we’re creating a factory that exposes a method which returns a form array; the familiar Formly form-fields that you’ll include in your directive.

Step 2: transfer your form fields from your controller

Your pre-refactored controller should look something like this:

Copy your form-field array to your new FormlyForms (createOrganization) method:

If you are using a nested object in your model, declare a model property in your form object so Formly know’s that it belongs to a sub-object.

Step 3: Replace your Formly form fields in your controller with the FormlyForms service

You can now relieve the bloat in your controller by simply calling in your new formly service in your controller (remember to include your service as a dependency)

Much better. Now your controller is cleaner, your forms are reusable across controllers, and everything is easier to reason about.

Extending the logic here, you should centralize all your forms into your FormlyForms service. Just expose a new method and you’re good to go:

Now you can call your new method in any controller and have it expose your form-fields. Now, when you need to edit a form, they are all in the same service so you know exactly where they live.