使用AngularJS,如何一次将所有表单字段设置为$ dirty?

Mat*_*att 16 angularjs

我使用AngularJS创建了一个HTML表单,并required为某些字段添加了属性.

对于这些领域,我有一个显示如果该字段不是错误消息$pristine,并且还$invalid:

<input type="text" ng-model="SomeModel.SomeProperty" name="myField" class="input-block-level" required>
<p ng-show="frmMyForm.myField.$invalid && !frmMyForm.myField.$pristine" class="error-text">This field is required!</p>
Run Code Online (Sandbox Code Playgroud)

这很好用.但是,如果用户只是跳过必填字段(从不将光标放在其中),则该字段始终是原始的,因此即使单击提交按钮后也不会显示错误消息.因此,用户面对的是他们无法提交的表单,但没有错误文本告诉他们原因.

我的想法是,将所有表单字段设置$dirty为提交操作将触发错误消息以显示用户只是跳过的任何必填字段.这可能吗?如果是这样,怎么样?

提前致谢.

Bey*_*ers 14

我们做了类似于你的回答的事情,我们有一个formSubmitted指令绑定到submit事件,如果触发我们在表单控制器上设置$ submitted变量.这样,您可以以与使用ShowValidationMessages的方式类似的方式使用它,但它可以重复使用.非常简单的指令:

app.directive('formSubmitted', [function () {
    return {
        restrict: 'A',
        require: 'form',
        link: function (scope, element, attrs, ctrl) {
            ctrl.$submitted = false;
            element.on('submit', function () {
                scope.$apply(function () {
                    ctrl.$submitted = true;
                });
            });
        }
    };
}]);
Run Code Online (Sandbox Code Playgroud)

您可以在表单标记本身上将其应用为属性.

我们进一步采取了几个步骤,我们的要求是仅在以下情况适用时显示验证错误:元素无效且表单已提交或输入元素已模糊.因此,我们最终得到另一个指令,该指令需要ngModel来设置ngModel控制器上元素的模糊状态.

最后在html中删除了大量重复的样板代码以检查所有这些内容,例如,ng-show="frmMyForm.myField.$invalid && (!frmMyForm.myField.$pristine || MyObject.ShowValidationMessages)"我们将其封装到指令中.此模板指令使用Bootstrap样板包装我们的输入元素,并处理所有验证内容.所以现在我的所有表单输入都遵循以下模式:

<div data-bc-form-group data-label="Username:">
    <input type="text" id="username" name="username" ng-model="vm.username" data-bc-focus required />
</div>
Run Code Online (Sandbox Code Playgroud)

和bcFormGroup指令将其转换为以下引导程序启用的html:

<div class="form-group" ng-class="{'has-error': showFormGroupError()}" data-bc-form-group="" data-label="Username:">
    <label for="username" class="col-md-3 control-label ng-binding">Username:</label>
    <div class="col-md-9">
        <input type="text" id="username" name="username" ng-model="vm.username" data-bc-focus="" required="" class="ng-pristine form-control ng-valid ng-valid-required">
        <span class="help-block ng-hide" ng-show="showRequiredError()">Required</span>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

这使得DRY保持干燥,并为支持哪种类型的输入提供了极大的灵活性.

更新:

这是bcFormGroup指令的基本列表.默认模板使用bootstrap的水平形式,但可以根据自己的喜好进行调整.

app.directive('bcFormGroup', ['$compile', '$interpolate', function ($compile, $interpolate) {
  return {
    restrict: 'A',
    template:
        '<div class="form-group" ng-class="{\'has-error\': showFormGroupError()}">' +
            '<label for="{{inputId}}" class="col-md-3 control-label">{{label}}</label>' +
            '<div class="col-md-9">' +
                '<bc-placeholder></bc-placeholder>' +
            '</div>' +
        '</div>',
    replace: true,
    transclude: true,
    require: '^form',
    scope: {
        label: '@',
        inputTag: '@'
    },

    link: function (scope, element, attrs, formController, transcludeFn) {

        transcludeFn(function (clone) {
            var placeholder = element.find('bc-placeholder');
            placeholder.replaceWith(clone);
        });

        var inputTagType = scope.inputTag || 'input';
        var inputElement = element.find(inputTagType);
        var fqFieldName = formController.$name + '.' + inputElement.attr('name');
        var formScope = inputElement.scope();

        if (inputElement.attr('type') !== 'checkbox' && inputElement.attr('type') !== 'file') {
            inputElement.addClass('form-control');
        }

        scope.inputId = $interpolate(inputElement.attr('id'))(formScope);
        scope.hasError = false;
        scope.submitted = false;

        formScope.$watch(fqFieldName + '.$invalid', function (hasError) {
            scope.hasError = hasError;
        });

        formScope.$watch(formController.$name + '.$submitted', function (submitted) {
            scope.submitted = submitted;
        });

        if (inputElement.attr('data-bc-focus') != null || inputElement.attr('bc-focus') != null) {
            scope.hasBlurred = false;
            formScope.$watch(fqFieldName + '.$hasBlurred', function (hasBlurred) {
                scope.hasBlurred = hasBlurred;
            });
        }

        if (inputElement.attr('required')) {
            scope.hasRequiredError = false;
            formScope.$watch(fqFieldName + '.$error.required', function (required) {
                scope.hasRequiredError = required;
            });
            inputElement.after($compile('<span class="help-block" ng-show="showRequiredError()">Required</span>')(scope));
        }

        if (inputElement.attr('type') === 'email') {
            scope.hasEmailError = false;
            formScope.$watch(fqFieldName + '.$error.email', function (emailError) {
                scope.hasEmailError = emailError;
            });
            inputElement.after($compile('<span class="help-block" ng-show="showEmailError()">Invalid email address</span>')(scope));
        }

        scope.showFormGroupError = function () {
            return scope.hasError && (scope.submitted || (scope.hasBlurred === true));
        };

        scope.showRequiredError = function () {
            return scope.hasRequiredError && (scope.submitted || (scope.hasBlurred === true));
        };

        scope.showEmailError = function () {
            return scope.hasEmailError && (scope.submitted || (scope.hasBlurred === true));
        };

    }
  };
}]);
Run Code Online (Sandbox Code Playgroud)

更新:

以下指令设置$ focused和$ hasBlurred:

app.directive('bcFocus', [function () {
    var focusClass = 'bc-focused';
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ctrl) {
            ctrl.$focused = false;
            ctrl.$hasBlurred = false;
            element.on('focus', function () {
                element.addClass(focusClass);
                var phase = scope.$root.$$phase;
                if (phase == '$apply' || phase == '$digest') {
                    ctrl.$focused = true;
                } else {
                    scope.$apply(function () {
                        ctrl.$focused = true;
                    });
                }
            }).on('blur', function () {
                element.removeClass(focusClass);
                var phase = scope.$root.$$phase;
                if (phase == '$apply' || phase == '$digest') {
                    ctrl.$focused = false;
                    ctrl.$hasBlurred = true;
                } else {
                    scope.$apply(function () {
                        ctrl.$focused = false;
                        ctrl.$hasBlurred = true;
                    });
                }
            });
        }
    };
}]);
Run Code Online (Sandbox Code Playgroud)


nic*_*ick 13

当表单无效时,FormController包含一个$error属性.

$error 是一个对象哈希,包含对具有失败验证器的控件或表单的引用.

所以你可以简单地遍历错误对象并在每个控件上使用NgModelController $setDirty():

// "If the name attribute is specified, the form controller is published onto the current scope under this name."
var form = scope.myForm;

if (form.$invalid) {
    angular.forEach(form.$error, function(controls, errorName) {
        angular.forEach(controls, function(control) {
            control.$setDirty();
        });
    });
}
Run Code Online (Sandbox Code Playgroud)


Mat*_*att 8

在发布此消息后不久,我想出了一个答案.我不确定它是否是正确的方法,但确实有效.

在您的控制器中,只需添加"ShowValidationMessages"或类似的属性,并将其设置为false:

$scope.MyObject = {
   ShowValidationMessages: false
};
Run Code Online (Sandbox Code Playgroud)

现在在字段级验证逻辑中引用此值:

<p ng-show="frmMyForm.myField.$invalid && (!frmMyForm.myField.$pristine || MyObject.ShowValidationMessages)" class="error-text">This field is required!</p>
Run Code Online (Sandbox Code Playgroud)

最后,将ShowValidationMessages属性切换到true表单提交功能:

    $scope.MyObject = {
       ShowValidationMessages: false,
       SubmitForm: function(){
            $scope.MyObject.ShowValidationMessages = true;
            if($scope.frmMyForm.$valid){
                //do stuff
            }    
       }
    };
Run Code Online (Sandbox Code Playgroud)