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

时间:2016-11-04 03:31:44

标签: javascript angularjs validation angular-material

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

我尝试过使用ngShow / Hide和$ valid / $无效的组合,但我似乎无法按照我需要的方式使用它。

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

2 个答案:

答案 0 :(得分:1)

我会将$untouched$error结合使用。 $untouched最初会显示提示。验证错误将导致模糊。从此时起,由于该字段被触及&#34;,除非输入无效,否则将显示提示。在你的情况下,这样的事情应该有效:

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

答案 1 :(得分:0)

请参阅此演示,它将为您提供帮助:http://plnkr.co/edit/lbiKfYbkZJWSu5oUmsAe?p=preview

如果字段为空,将显示<错误消息',否则将显示“提示消息”。以下是相关的HTML&amp; 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;
  };
});