ES-DOC / esdoc-questionnaire

ES-DOC Questionnaire (webform generator for creating CIM Documents). POC: @allynt
Other
2 stars 1 forks source link

Disable form submission buttons based on form validity. #454

Open allynt opened 8 years ago

allynt commented 8 years ago

WHO: @allynt

Disable form submission buttons based on form validity. Ordinarily, this is very simple in Angular:

<form name="my_form">
   ...some fields...
</form>
<button ng-click="do_something" ng-disabled="my_form.$invalid">ok</button>

However, in the Q there are loads of forms most of which are created dynamically. This means I need to come up w/ a way to:

  1. bind the "ng-disabled" attribute to a fn that checks the state of all loaded forms (in the case of the main form "save" button)
  2. bind the "ng-disabled" attribute to the state of a specific form without knowing its name (in the case of modal forms (like the category & subform customization forms)
allynt commented 8 years ago

This can be done w/ directives:

app.js:


    app.directive('watchFormValidity', function() {
        return {
            restrict: "A", 
            link: function (scope, element, attrs) {
                var scope_variable = attrs["watchFormValidity"];
                var form_name = attrs["name"];
                var form_validity_expression = form_name + ".$valid";
                scope.$watch(form_validity_expression, function (form_validity) {
                    scope[scope_variable] = form_validity;
                }, true);
            }
        }
    });

template.html:

<form name="whatever" watch_form_validity="some_variable_to_watch">
  ...some fields...
</form>
<button ng-disabled="!some_variable_to_watch">ok</button>

This will work fine for modal forms. And for the main form, I can write a fn to AND all of these scope variables together.

I am a JavaScript god!

allynt commented 8 years ago

Although the above code works, those "variables_to_watch" exist in isolated ng controllers w/ isolated scopes. I need to figure out how to access them all together if I am to AND them together.

allynt commented 7 years ago

Just learned that ng-form is nestable, which means that the .$validity of the parent form will take into account the .$validity of all its children, which means that I still ought to be able to use my clever watch_form_validity directive.