Skip to content
This repository has been archived by the owner on Apr 30, 2018. It is now read-only.

Tips & Tricks

Kent C. Dodds edited this page Mar 27, 2015 · 6 revisions

Below are some tips and tricks from members in the community. Please feel free to add sections or make other changes here as needed!

ng-form vs form

The formly-form directive uses ng-form under the hood. This allows you to nest forms which you cannot do with the regular form element. However, this also means that you're not able to use ng-submit on a formly-form either. This really stinks from an accessibility standpoint. However, you can augment ng-form itself to simulate this type of behavior like so:

(function() {
    'use strict';

    angular.module('app').directive('ngForm', ngForm);

    function ngForm() {
        return {
            restrict: 'E',
            link: function(scope, element, attrs) {
                var ngForm = scope.$eval(attrs.name);
                if (ngForm) {
                    ngForm.formlyDemoSubmit = function() {
                        if (ngForm.$invalid) {
                            return;
                        }
                        var context = scope.$parent;
                        ngForm.formlyDemoSubmitting = context.$eval(attrs.ngSubmit);
                        return ngForm.formlyDemoSubmitting;
                    };
                    element.on('keyup', function(event) {
                        if (event.which === 13 && attrs.ngSubmit) {
                            submitFormFromEvent(event);
                        }
                    });
                    var submitButton = angular.element(element[0].querySelectorAll('[type=submit]'));
                    if (submitButton.length === 1) {
                        submitButton.on('keyup', function(event) {
                            if (event.which === 32 || event.which === 13) {
                                submitFormFromEvent(event);
                            }
                        });
                        submitButton.on('click', submitFormFromEvent);
                    } else if (submitButton.length) {
                        throw new Error('Forms should only have one submit button');
                    }
                }

                function submitFormFromEvent(event) {
                    /* jshint -W030 */
                    event && event.preventDefault && event.preventDefault();
                    event && event.stopPropagation && event.stopPropagation();
                    ngForm.formlyDemoSubmit();
                    scope.$apply();
                }
            }
        };
    }
})();

Now you can use ng-submit on any formly-form and the button of type submit will submit the form as expected (for example):

<formly-form result="user" fields="userFields" ng-submit="save(user)">
  <button type="submit">Submit</button>
</formly-form>
Clone this wiki locally