如何在没有提交按钮AngularJS的情况下将所有输入设置为$touch

how to set all inputs as $touched without submit button AngularJS

本文关键字:输入 设置 情况下 touch 提交 AngularJS 按钮      更新时间:2023-09-26

我有一个指令,它根据表单中的$valid$untouched属性验证表单中的输入-如果输入被"触摸",它会检查验证,并相应地将字体和边框涂成红/绿,如果输入没有被"触摸",它将不会执行任何操作。

我使用ngBootBox的自定义对话框,所以我没有type="submit"类型的按钮来提交表单,我使用"创建"按钮的回调函数来传递/保存数据。

我的问题是,当我单击"创建"按钮时,表单不是"有效"的,因为有些字段是空的——我的输入仍然是"未动的",所以$watch函数没有被调用。有什么解决方案吗?有没有这样的方法:$scope.createProjectForm.$setTouched(true);,它将使该表单的所有子输入都获得该值?

我也试过了,但没有成功:

angular.forEach($scope.createProjectForm, function(field){
   field.$setTouched(true);
});

这是我的验证指令:

angular.module('mean.theme').directive("inputValidation", function () {
    return {
        restrict: 'EA',
        require: 'ngModel',
        link: function (scope, inputElement, attrs, ngModelCtrl) {
            var $icon = $('<i class="fa"></i>');
            inputElement.before($icon);
            scope.$watchGroup([
                function(){
                    return ngModelCtrl.$untouched;
                },
                function(){
                    return ngModelCtrl.$valid;
                }
            ], function(Paramaters){
                console.log(scope);
                if(!Paramaters[0]) {
                    if (Paramaters[1]) {
                        inputElement.switchClass('validation-warning-border','validation-success-border',50)
                        inputElement.prev().switchClass('fa-warning validation-warning-font' , 'fa-check validation-success-font',50);
                    } else {
                        inputElement.switchClass('validation-success-border','validation-warning-border',50)
                        inputElement.prev().switchClass('fa-check validation-success-font','fa-warning validation-warning-font',50)
                    }
                }
            });
        }
    };
});

这是我的控制器代码的一部分:

    $scope.create = function () {
        var options = {
            title: 'Create',
            templateUrl: 'project.html',
            scope: $scope,
            buttons: {
                warning: {
                    label: "Cancel",
                    className: "btn-link",
                    callback: function () {
                    }
                },
                success: {
                    label: "Create",
                    className: "green",
                    callback: function () {
                        if ($scope.createProjectForm.$valid){
                            $scope.createProject(template);
                        } else {
                            $scope.project.createButtonClicked = true;
                            return false;
                        }
                    }
                }
            }
        };
        $ngBootbox.customDialog(options);
    };

这是我HTML代码的一部分:

<form role="form" name="createProjectForm">
    <label>
        Name Your Project
    </label>
    <div>
        <input type="text" name="project.name"
               ng-model="project.name" required="required" class="form control" input-validation/>
    </div>
    <label>
        Name Your Project
    </label>
    <div>
        <input type="text" name="project.title"
               ng-model="project.title" required="required" class="form control" input-validation/>
    </div>
</form>
  • 编辑:

我找到了我需要的,更简单、更短的方法:

可以手动设置:$scope.createProjectForm.$setSubmitted()true

然后使子(输入)$watch也用于该改变:

scope.$watchGroup([
            function(){
                return ngModelCtrl.$untouched;
            },
            function(){
                return ngModelCtrl.$valid;
            },
            function(){
                return ngModelCtrl.$$parentForm.$submitted;
            }
        ], function(Paramaters){
         // code here
        }

您可以使用类似的格式:

if ($scope.form.$invalid) {
    angular.forEach($scope.form.$error, function (field) {
        angular.forEach(field, function(errorField){
            errorField.$setTouched();
        });
    });
}

请参阅"$setTouched":https://docs.angularjs.org/api/ng/type/ngModel.NgModelController

对于嵌套表单:

function setFormTouched(form) {
        // Check if the form/property has the $setSubmitted method
        if (form.hasOwnProperty('$submitted')) {
            // Iterate through each of the required error properties
            angular.forEach(form.$error, function (errorType) {
                // Iterate through each error type
                angular.forEach(errorType, function (prop) {
                    // Check if the property has the $setTouched method
                    if (prop.hasOwnProperty('$touched')) prop.$setTouched();
                    // Recursive call to handle nested forms
                    setFormTouched(prop);
                });
            });
        }
    }

解决方案基于Patrick Marabeas的codepen,但我不得不编辑原始代码,因为hasOwnProperty不适用于原型中定义的函数。例如:

if(prop.hasOwnProperty('$setTouched'))

始终返回false。

编辑:我最初需要的是一种让用户更容易在嵌套选项卡中查找错误的方法。这是用于禁用/启用提交按钮和错误消息的最终工作范围功能:

$scope.isFormValid = function (topLevelForm) {
        if (topLevelForm.$valid) {
            return true;
        }
        // Form not valid, triggering fields to make it easier to find errors
        setFormTouched(topLevelForm);
        function setFormTouched(form) {
            // Check if the form/property has the $setSubmitted method
            if (form.hasOwnProperty('$submitted')) {
                // Iterate through each of the required error properties
                angular.forEach(form.$error, function (errorType) {
                    // Iterate through each error type
                    angular.forEach(errorType, function (prop) {
                        // Check if the property has the $setTouched method
                        if (prop.hasOwnProperty('$touched')) prop.$setTouched();
                        // Recursive call to handle nested forms
                        setFormTouched(prop);
                    });
                });
            }
        }
        return false;
    };