【问题标题】:Error validation not working in AngularJS错误验证在 AngularJS 中不起作用
【发布时间】:2016-07-24 21:01:06
【问题描述】:

我在 Angular 中进行错误验证,如下所示。

<select ng-model = "$parent.color" class = "form-control"
    ng-options = "color as color for color in $parent.colors" required>
    <option value="">Choose an option</option> 
</select>

<span ng-show="serviceForm.$parent.color.$error.required"> My custom error message </span>

错误验证消息永远不会出现。如何解决这个问题?

【问题讨论】:

    标签: javascript html angularjs error-handling ng-show


    【解决方案1】:

    您是否包含了 ngRequire 模块?

    ngRequire

    <script>
    angular.module('ngRequiredExample', [])
    .controller('ExampleController', ['$scope', function($scope) {
      $scope.required = true;
    }]);
    </script>
    <div ng-controller="ExampleController">
     <form name="form">
     <label for="required">Toggle required: </label>
     <input type="checkbox" ng-model="required" id="required" />
     <br>
     <label for="input">This input must be filled if `required` is true:</label>
     <input type="text" ng-model="model" id="input" name="input" ng-required="required" /> <br>
     <hr>
     required error set? = <code>{{form.input.$error.required}}</code><br>
     model = <code>{{model}}</code>
    

    如果可行,试试这个。

    【讨论】:

      【解决方案2】:

      您的代码可以像这样才能正常工作。

      <form name="form1">
         <select name="select" ng-model = "$parent.color" class = "form-control"
             ng-options = "color as color for color in $parent.colors" required>
             <option value="">Choose an option</option>    
         </select>
         <span ng-show="form1.select.$error.required"> My custom error message </span>
      </form>
      

      你不是在流动 FormController。查看此link

      【讨论】:

      • 有没有办法让消息只在提交时显示?现在它总是显示
      • 是的,您可以使用范围变量作为提交的标志,在调用提交时将其提高,否则将其设为假。并在 ng-show 条件下使用它以及 && 运算符。 Ex $scope.submitted
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多