AngularJS <input />验证,没有封闭的<form> </form>

时间:2014-02-28 15:00:05

标签: angularjs validation

Angular中是否有可能以类似的方式验证单个隔离的<input>表单的验证?我正在考虑这样的事情:

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

上面的例子不起作用。将其封装在<form>中并将ng-show替换为ng-show="myForm.myInput.$error.maxlength"会有所帮助。

是否可以在不使用<form>的情况下执行此操作?

3 个答案:

答案 0 :(得分:177)

您可以使用ng-form角度指令(see docs here)对任何内容进行分组,甚至可以在html表单之外进行分组。然后,您可以利用角度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

答案 1 :(得分:0)

以Silvio Lucas为基础&#39;回答,如果你在循环中迭代并且需要能够插入表单名称和有效状态:

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

答案 2 :(得分:-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>