有没有办法在没有表格的情况下使用角度输入验证。见角plunker。当我将<form name="myForm">
更改为<div name="myForm">
时,验证将不再有效。
HTML:
<form name="myForm">
<label>
User name:
<input type="text" name="userName" ng-model="user.name" required>
</label>
<div role="alert">
<span class="error" ng-show="myForm.userName.$error.required">
Required!</span>
</div>
<label>
Last name:
<input type="text" name="lastName" ng-model="user.last" ng-minlength="3" ng-maxlength="10">
</label>
<div role="alert">
<span class="error" ng-show="myForm.lastName.$error.minlength">Too short!</span>
<span class="error" ng-show="myForm.lastName.$error.maxlength">Too long!</span>
</div>
</form>
答案 0 :(得分:3)
您需要拥有form指令,因为ngModel会搜索其控制器,以便自行注册并利用验证功能。
如果出于布局原因,您无法使用表单标记(嵌套的<form>
标记无效),那么您可以使用ngForm指令来实现相同的效果:
<ng-form name="myForm">
<label>
User name:
<input type="text" name="userName" ng-model="user.name" required>
</label>
<div role="alert">
<span class="error" ng-show="myForm.userName.$error.required">
Required!</span>
</div>
<label>
Last name:
<input type="text" name="lastName" ng-model="user.last"
ng-minlength="3" ng-maxlength="10">
</label>
<div role="alert">
<span class="error" ng-show="myForm.lastName.$error.minlength">
Too short!</span>
<span class="error" ng-show="myForm.lastName.$error.maxlength">
Too long!</span>
</div>
</ng-form>