隐藏AngularJs中的默认错误消息

时间:2016-05-15 20:59:22

标签: javascript jquery css angularjs hide

如何在AngularJs中隐藏默认错误消息?我试过 display:none; 。但是,它不会起作用。我是AngularJS的新手。我想隐藏默认的错误消息,我想在用户onfocus输入文本框时显示错误消息。

<p>
    <label for="first_name">First Name</label>
    <input type="text" name="first_name" id="first_name" ng-model="firstName" ng-pattern="/^[a-zA-Z\s]*$/" required/>
    <span class="error" ng-messages="contact_form.first_name.$error">
        <span ng-message="required">First name should not be empty</span>
        <span ng-message="pattern" ng-show="contact_form.first_name.$error.pattern">Only alphabets allowed</span>
    </span>
</p>

2 个答案:

答案 0 :(得分:3)

这是您所需要的,contact_form.first_name.$dirty用于检查字段是否已更改

<form name="contact_form" novalidate>    
  <p>
      <label for="first_name">First Name</label>
      <input type="text" name="first_name" id="first_name" ng-model="firstName" ng-pattern="/^[a-zA-Z\s]*$/" required/>
      <span class="error" ng-messages="contact_form.first_name.$error">
          <span ng-message="required" ng-show="contact_form.first_name.$error.required && contact_form.first_name.$dirty">First name should not be empty</span>
          <span ng-message="pattern" ng-show="contact_form.first_name.$error.pattern">Only alphabets allowed</span>
      </span>
  </p>
</form>

答案 1 :(得分:1)

在您的控制器中,您可以创建一个变量来确定表单是否已被汇总:

app.controller('NameController', ['$scope', function($scope) {
    $scope.submitted = false;

    $scope.formProcess = function(form) {
    $scope.submitted = true;
        // logic
    }
}]);

比在你看来:

<form ng-submit="formProcess(form)">
    <p>
        <label for="first_name">First Name</label>
        <input type="text" name="first_name" id="first_name" ng-model="firstName" ng-pattern="/^[a-zA-Z\s]*$/" required/>
        <span class="error" ng-if="submitted" && ng-messages="contact_form.first_name.$error">
            <span ng-message="required">First name should not be empty</span>
            <span ng-message="pattern" ng-show="contact_form.first_name.$error.pattern">Only alphabets allowed</span>
        </span>
    </p>
    <p>
        <button class="btn btn-secondary" type="submit">Send</button>
    </p>
</form>