没有包含<form>的AngularJS <input>validation

是否有可能在Angular中validation一个单独的<input>类似的方式来validation表单? 我正在考虑这样的事情:

 <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="myForm.myInput.$error.maxlength"ng-show="myForm.myInput.$error.maxlength"replaceng-show

有没有可能做到这一点,而不使用<form>

您可以使用ng-form angular指令( 请参阅此处的文档 )对任何内容进行分组,即使在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> 

build立在西尔维奥卢卡斯的答案,如果你迭代循环,需要能够插入表单名称和有效状态:

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