在Angular中隐藏/显示提示文本

Hiding/showing hint text in Angular

本文关键字:显示 提示 文本 隐藏 Angular      更新时间:2023-09-26

如果$error上的输入没有错误,我想在输入下面显示一些提示文本。因此,要么显示提示文本,要么在出现错误时显示错误消息。

我试过使用ngShow/Hide和$valid/$invalid的组合,但我似乎不能让它按我需要的方式工作。

<div ng-form="reg.form" name="reg.form" novalidate>
   <md-input-container flex="100">
      <label>{{"views.application.mobile.label" | translate}}</label>
      <input type="tel" ng-model="reg.user.mobile" name="mobile" required
             ng-pattern="/(^04('s?[0-9]{2}'s?)([0-9]{3}'s?[0-9]{3}|[0-9]{2}'s?[0-9]{2}'s?[0-9]{2})$)/">
      <div ng-show="???" class="hint">e.g. 0400123123</div>
      <div ng-messages="reg.form.mobile.$error">
        <p class="help-block" ng-message="required">{{"views.application.mobile.error.required" | translate}}</p>
        <p class="help-block" ng-message="pattern">{{"views.application.mobile.error.invalid" | translate}}</p>
      </div>
    </md-input-container>
</div>

我将$untouched$error结合使用。$untouched将首先显示提示。验证错误将在模糊时出现。从这一点开始,由于字段被"触摸",除非输入无效,否则将显示提示。在您的情况下,应该这样做:

<div ng-show="reg.form.mobile.$untouched || (!reg.form.mobile.$error.required && !reg.form.mobile.$error.pattern)"
    class="hint">
    e.g. 0400123123
</div>

看看这个演示,它会帮助你:http://plnkr.co/edit/lbiKfYbkZJWSu5oUmsAe?p=preview

如果字段为空,将显示'Error message',否则将显示'hint message'。下面是相关的HTML &JS代码

HTML:

<!DOCTYPE html>
<html ng-app="plunker">
  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.5.x" src="https://code.angularjs.org/1.5.8/angular.js" data-semver="1.5.8"></script>
    <script src="app.js"></script>
  </head>
  <body ng-controller="MainCtrl">
    <form name="userForm" novalidate>
      <label>
        First Name: <br/>
        <input name="firstname" type="text" ng-model="user.firstName" required><br />
        <span class="error" ng-show="userForm.firstname.$error.required">Please enter First name<br /></span>
        <span class="hint" ng-show="!userForm.firstname.$error.required">Hint: First name cannot left blank<br /></span><br />
      </label>
      <label>
        Last Name: <br/>
        <input name="lastname" type="text" ng-model="user.lastName" required><br />
        <span class="error" ng-show="userForm.lastname.$error.required">Please enter Last name<br /></span>
        <span class="hint" ng-show="!userForm.lastname.$error.required">Hint: Last name cannot left blank<br /></span><br />
      </label>
      <button ng-click="submitUser()">Submit</button>&nbsp;<button>Cancel</button>
    </form>
    <pre>{{ user|json }}</pre>
  </body>
</html>

JS:

var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
  $scope.isSubmitted = false;
  $scope.submitUser = function() {
    $scope.isSubmitted = true;
  };
});