AngularJS<输入>没有封闭 <form> 的验证 [英] AngularJS <input> validation with no enclosing <form>

查看:31
本文介绍了AngularJS<输入>没有封闭 <form> 的验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

<input name="myInput" type="text" class="form-control" ng-model="bindTo" ng-maxlength="5"><span class="error" ng-show="myInput.$error.maxlength">太长了!</span>

上面的例子不起作用.将其包含在

中并将 ng-show 替换为 ng-show="myForm.myInput.$error.maxlength" 有帮助.

不使用是否可以做到这一点?

解决方案

您可以使用 ng-form angular 指令 (请参阅此处的文档) 以对任何内容进行分组,即使是在 html 表单之外.然后,您可以利用 angular FormController.

<input name="myInput" type="text" class="form-control" ng-model="bindTo" ng-maxlength="5"><span class="error" ng-show="myForm.myInput.$error.maxlength">太长了!</span>

示例

Is it possible in Angular to validate a single, isolated <input> in a similar way the forms are validated? I'm thinking about something like this:

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

The example above doesn't work. Enclosing it in a <form> and replacing ng-show with ng-show="myForm.myInput.$error.maxlength" helps.

Is it possible to do this without using <form>?

解决方案

You may use the ng-form angular directive (see docs here) to group anything, even outside a html form. Then, you can take advantage from 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

这篇关于AngularJS&lt;输入&gt;没有封闭 &lt;form&gt; 的验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆