Development 01 Dec 2017 3 min read

Getting Started with AngularJS: Working with Forms | Magora-Systems

Artem Efremov
Artem Efremov
Team Lead/ Senior Software Engineer
Getting Started with AngularJS: Working with Forms 01 Dec 2017

Hello again! As promised, here's a post to follow my previous article. This time, I'll talk about a way of eliminating the necessity to write boilerplate code

Hello again! As promised, here's a post to follow my previous article. This time, I'll talk about a way of eliminating the necessity to write boilerplate code for your projects.

The basics

AngularJS is a framework that supports module structure, which allows creating independent modules. Let’s break down the approach using forms as an example. Now, what is required for forms to work?

  1. View - for displaying fields
  2. Validation - for checking input data
  3. Data processing

The first two items will appear in every project, as 90% of forms look alike. Let’s make a form into a component that will take care of display and validation. Component responsible for validation we’ll get from our repository. We can divide form generator into 2 modules:

  1. The first one is the form itself. It will process our data object and launch function, if the form is filled out correctly.
  2. The second one is responsible for field rendering and validation.
I suggest using the following structure to describe data for generation:
this.model = {
            url: 'sign-in',
            submit: function (data) {

            },
            rules: {
                email: {
                    type: 'invalid',
                    message: 'Email error',
                    rule: function (form, field) {
                        var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
                        return field.$dirty && !re.test(field.$modelValue);
                    }
                }
            },
            attr: {
                identifier: {
                    type: 'text',
                    attr: {placeholder: 'Your email or phone number'},
                    validators: ['required', 'email']
                },
                gender: {
                    type: 'select',
                    value: 'man',
                    options: [{
                        name: 'Man',
                        value: 'man'
                    }, {
                        name: 'Woman',
                        value: 'woman'
                    }],
                    attr: {placeholder: 'Your email or phone number'},
                    validators: ['required']
                },
                password: {
                    type: 'password',
                    attr: {placeholder: 'Your password'},
                    validators: ['required']
                }
            },
            buttons: {
                submit: {
                    text: "Sign in"
                }
            }
        };
Rules allow setting up a custom validator, attr stores a list of our fields. The form will initialize upon calling the directive:
body
        div(ng-controller="demoCtrl as ctrl")
            mgr-form-builder(model="ctrl.model")
Perhaps, at this point you'll have a valid question: “How can I customize View for a unique form?” For that you’ll need to simply add URL of a new form template using templateUrl attribute:
scope: {
                model: '=',
                formName: '=',
                templateUrl: '@'
            },
            templateUrl: function (el, attr) {
                if (attr.templateUrl) {
                    return attr.templateUrl;
                }
                return 'formBuilder/formBuilder.html';
            },
As far as displaying goes, everything is pretty much clear. But now there’s another question to answer: how do we get data after a form's been successfully filled out? For that, let’s add a function that runs upon “submit” event:
formBuilderCtrl.submit = function () {

                    if (!formBuilderCtrl.model.submit) {
                        return false;
                    }

                    var data = {};
                    Object
                        .keys(formBuilderCtrl.model.attr)
                        .forEach(function (key) {
                            data[key] = formBuilderCtrl.model.attr[key].value;
                        });

                    formBuilderCtrl.model.submit(data);
                };
Now all we need to do is mention our function in the module. Once a form is completed, submit function will be performed and we’ll get the data added by user.

Result

We have a component that we can use from project to project and we don't have to worry about how or what to validate. We just need to describe data model. Want to learn more? Take a peek into our repository.
Artem Efremov

Artem Efremov

Team Lead/ Senior Software Engineer

Meet Artem, the dynamic force behind Magora's Development team and the success of our clients' projects. With a genuine passion for technology and a deep understanding of his team's strengths, Artem fosters a collaborative environment where creativity flourishes. His dedication to excellence and personal touch ensure that every project exceeds expectations, leaving a lasting impact on both clients and colleagues alike.

LinkedIn
— Newsletter

Get the next one in your inbox.

One email a month. Practical, no fluff. Unsubscribe anytime.

— Cookies

We use cookies to measure traffic and make our marketing more relevant. Necessary cookies stay on. See our Privacy and Cookie Notice.

Free 30-min consult Free consult