如何将所有输入设置为$ touch而不提交按钮AngularJS

时间:2015-12-08 19:14:42

标签: javascript angularjs forms

我有一个指令,根据$valid$untouched属性验证表单中的输入 - 如果输入是"触及"它检查验证并相应地将字体和边框用红色/绿色着色,如果输入没有触及"它什么都做不了。

我使用ngBootBox的自定义对话框,因此我没有提交表单的type="submit"按钮,我使用&的回调功能#34;创建"按钮以传递/保存数据。

我的问题是当我点击"创建"按钮和表单不是"有效"因为有些字段是空的 - 我的输入仍然是"未被触及"所以$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
        }

2 个答案:

答案 0 :(得分:9)

您可以遵循与此类似的格式:

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

请参阅&#39; $ setTouched&#39;:https://docs.angularjs.org/api/ng/type/ngModel.NgModelController

答案 1 :(得分:2)

对于嵌套表单:

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;
    };