Getting Started with AngularJS: Working with Forms

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.
Dmitry K.
December 02, 2017
related
App Cost Calculator Eight Hot Questions about Mobile App Developers Top 7 Educational App Ideas to Broaden your Horizons
recent
Eight Hot Questions about Mobile App Developers Top 7 Educational App Ideas to Broaden your Horizons SEO: How to Optimise your Website for Google Image Search
recommended
Everything You Want to Know About Mobile App Development App Development Calculator Infographics: Magora development process Dictionary
categories
News Technologies Design Business Development
Logo Magora LTD
close
Get in touch
Do you agree to the personal data processing?

Logo Magora LTD
close
Thank you very much.

Your registration to the webinar on the 27th of September at 2 p.m. BST was successfuly completed.
We will send you a reminder on the day before the event.
Magora team
Registration for a webinar

"Let Smart Bots Speed up your Business"
Date: 27.09.2018 Time: 2 p.m. BST
Do you agree to the personal data processing?