【问题标题】:AngularJS <input> validation with no enclosing <form>没有封闭 <form> 的 AngularJS <input> 验证
【发布时间】:2014-04-01 15:46:26
【问题描述】:

是否可以在 Angular 中以类似于验证表单的方式验证单个隔离的 &lt;input&gt;?我正在考虑这样的事情:

<div class="form-group">
    <input name="myInput" type="text" class="form-control" ng-model="bindTo" ng-maxlength="5">
    <span class="error" ng-show="myInput.$error.maxlength">Too long!</span>
</div>

上面的例子不起作用。将其包含在 &lt;form&gt; 中并将 ng-show 替换为 ng-show="myForm.myInput.$error.maxlength" 会有所帮助。

不使用&lt;form&gt;是否可以做到这一点?

【问题讨论】:

标签: angularjs validation


【解决方案1】:

您可以使用 ng-form angular 指令 (see docs here) 对任何内容进行分组,即使是在 html 表单之外。然后,您可以利用 Angular FormController。

<div class="form-group" ng-form name="myForm">
    <input name="myInput" type="text" class="form-control" ng-model="bindTo" ng-maxlength="5">
    <span class="error" ng-show="myForm.myInput.$error.maxlength">Too long!</span>
</div>

Example

【讨论】:

【解决方案2】:
<!DOCTYPE html>
<html ng-app="plunker">
<head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js">   </script>

</head>

<body ng-controller="MainCtrl">
    <div class="help-block error" ng-show="test.field.$error.required">Required</div>
    <div class="help-block error" ng-show="test.firstName.$error.required">Name Required</div>
    <p>Hello {{name}}!</p>
    <div ng-form="test" id="test">
        <input type="text" name="firstName" ng-model="firstName" required> First name <br/> 
        <input id="field" name="field" required ng-model="field2" type="text"/>
    </div>
</body>
<script>
    var app = angular.module('plunker', []);

    app.controller('MainCtrl', function($scope) {
      $scope.name = 'World';
      $scope.field = "name";
      $scope.firstName = "FirstName";
      $scope.execute = function() {
        alert('Executed!');
      }
    });

</script>

【讨论】:

【解决方案3】:

基于 Silvio Lucas 的回答,如果您在循环中进行迭代并且需要能够插入表单名称和有效状态:

<div
  name="{{propertyName}}"
  ng-form=""
  class="property-edit-view"
  ng-class="{
    'has-error': {{propertyName}}.editBox.$invalid,
    'has-success':
      {{propertyName}}.editBox.$valid &&
      {{propertyName}}.editBox.$dirty &&
      propertyValue.length !== 0
  }"
  ng-switch="schema.type">
  <input
    name="editBox"
    ng-switch-when="int"
    type="number"
    ng-model="propertyValue"
    ng-pattern="/^[0-9]+$/"
    class="form-control">
  <input
    name="editBox"
    ng-switch-default=""
    type="text"
    ng-model="propertyValue"
    class="form-control">
  <span class="property-type" ng-bind="schema.type"></span>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-18
    • 2018-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多