Unsubmit a form in Angular

2020-04-12 04:19发布

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?

2条回答
相关推荐>>
2楼-- · 2020-04-12 04:25

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

查看更多
做自己的国王
3楼-- · 2020-04-12 04:40

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

查看更多
登录 后发表回答