Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unsubmit a form in Angular

I need a form to be able to be both $dirty and not $submitted for my validation to work.

I'm trying to accomplish this through CSS using the .ng-invalid, .ng-dirty, and .ng-submitted classes that get dynamically added by angular. This means I cannot simply set $submitted to false on the form as this will not remove the associated class. Nor can I use $setPristine or $setUntouched as these will remove the $dirty flag and its class.

Is there some way to set a form as unsubmitted so that the .ng-submitted class is removed AND the form remains dirty?

like image 307
TomSlick Avatar asked Feb 09 '23 05:02

TomSlick


2 Answers

You can use $setPristine followed by $setDirty. If you want to retain the $dirty value, save it before setting it to pristine.

var formWasDirty = form.$dirty;

form.$setPristine(); 

if (formWasDirty) { 
  form.$setDirty();
}

http://plnkr.co/edit/nCgu7eBWAXwO3xeYTa6V?p=preview

like image 144
Jan Avatar answered Feb 11 '23 19:02

Jan


Unfortunately, there isn't a built in $setUnsubmitted function in Angular.

However, the source for the $setSubmitted function is very simple. You can easily leverage a decorator on the form directive to provide this functionality.

angular.module('YourModule').directive('form', function() {
    return {
        require: 'form',
        link: function(scope, element, attrs, form) {
            form.$setUnsubmitted = function() {
                element.removeClass('ng-submitted');
                form.$submitted = false;
                if (form.$$parentForm.$setUnsubmitted) { // may be nullFormCtrl
                    form.$$parentForm.$setUnsubmitted();
                }
            };
        }
    };
});

Should the Angular team choose the include this method in the future, you would simply remove this decorator with no changes to other code.

Plunk example here

like image 31
Taylor Buchanan Avatar answered Feb 11 '23 19:02

Taylor Buchanan