AngularJS:隐藏ng-message,直到点击form-submit按钮 [英] AngularJS: Hiding ng-message until hitting the form-submit button

查看:83
本文介绍了AngularJS:隐藏ng-message,直到点击form-submit按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是在AngularJS(1.x)中使用ng-messages的典型示例:

This is a typical example of the use of ng-messages in AngularJS (1.x):

<form name="demoForm">
  <input name="amount" type="number" ng-model="amount" max="100" required>

  <div ng-messages="demoForm.amount.$error">
    <div ng-message="required">This field is required</div>
  </div>

  <button type="submit">test submit</button>
</form>

请参阅: http://jsfiddle.net/11en8swy/3/

我现在想更改此示例,以便仅在触摸($touched)用户单击提交按钮时显示此字段为必填"错误.

I now want to change this example so the "This field is required" error only shows when the field is touched ($touched) or the user hits the submit button.

我不能在表单上使用ng-submitted类,因为验证错误阻止了表单的提交.

I cannot use the ng-submitted class on the form since the validation error prevents the submitting of the form.

我应该怎么做?

谢谢

推荐答案

您可以使用ng-show:

<div ng-messages="demoForm.amount.$error" ng-show="demoForm.amount.$touched">
    <div ng-message="required">This field is required</div>
</div>

并使用自定义指令.观看有效的演示:

And use a custom directive. See a working demo:

var app = angular.module('app', ['ngMessages']);

app.controller('mainCtrl', function($scope) {

});
app.directive('hasFocus', function($timeout) {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, element, attr, ctrl) {
      element.on('focus', function() {
        $timeout(function() {
          ctrl.hasFocusFoo = true;
        })
      });

      element.on('blur', function() {
        $timeout(function() {
          ctrl.hasFocusFoo = false;
        })
      });
    }
  }
})

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-messages.js"></script>

<body ng-app="app" ng-controller="mainCtrl">
  <form name="demoForm">
    <input name="amount" type="number" ng-model="amount" max="100" required has-focus>

    <div ng-messages="demoForm.amount.$error" ng-show="demoForm.amount.$touched || demoForm.amount.hasFocusFoo">
      <div ng-message="required">This field is required</div>
    </div>

    <button type="submit">test submit</button>
  </form>
</body>

该指令基本上是在ngModel控制器上设置另一个hasFocusFoo字段,然后我们可以轻松地使用该指令.

The directive is basically setting another hasFocusFoo field on the ngModel controller then we can easily use that directive.

这篇关于AngularJS:隐藏ng-message,直到点击form-submit按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆