javascript 当有标准的 maxlength 时,为什么 Angular 提供 ng-maxlength?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26907669/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why does Angular provide ng-maxlength when there is a standard maxlength?
提问by Den
HTML providesa standard maxlength attribute since version 4.01. Angular provides a ng-maxlengthdirective.
自 4.01 版起,HTML提供了标准的 maxlength 属性。Angular 提供了一个ng-maxlength指令。
The difference is that the standard approach doesn't allow entering more than max, while Angular's approach just generates a validation error.
不同之处在于标准方法不允许输入超过 max 的值,而 Angular 的方法只会生成验证错误。
Why did they decide to include such a directive? It's not because of dynamic data binding of maxlength since the behaviour is inconsistent. It's not because of compatibility since it's available even in HTML 4.01. My only guess is that it's there to provide an alternative validation paradigm, but it sounds like over-engineering.
他们为什么决定包含这样的指令?这不是因为 maxlength 的动态数据绑定,因为行为不一致。这不是因为兼容性,因为它甚至在 HTML 4.01 中也可用。我唯一的猜测是它提供了一种替代验证范式,但这听起来像是过度设计。
采纳答案by KanhuP2012
Not only it provide validation for max length, it also adds a class ng-invalid-maxlength
.
so when you put anything beyond the limit ng-invalid-maxlength
class will placed there
and in that class you can write your own css.
它不仅提供最大长度的验证,还添加了一个类ng-invalid-maxlength
。所以当你放任何超出限制的东西时,ng-invalid-maxlength
类都会放在那里,在那个类中你可以编写自己的 css。
So after key press if validation fails, the css will be invoked simultaneously and reflects on your UI.
因此,如果验证失败,按下按键后,css 将同时被调用并反映在您的 UI 上。
回答by fabbb
The previous answer may of been correct in earlier versions of angular but as of today and Angular v1.5.5, it looks like maxlength
does exactly the same thing as ng-maxlength
but also enforces the HTML inputs maxlength property on inputs of type text.
先前的答案在早期版本的 angular 中可能是正确的,但从今天和 Angular v1.5.5 开始,它看起来与maxlength
执行完全相同的事情,ng-maxlength
但也对文本类型的输入强制执行 HTML 输入 maxlength 属性。
Example:
例子:
<input type="text" maxlength=5>
maxlength
will enforce a 5 character max on the input and also add the correct angular validation class to the input.
maxlength
将对输入强制执行最多 5 个字符,并将正确的角度验证类添加到输入。
Whereas ngMaxlength
will only enforce validation. See: https://docs.angularjs.org/api/ng/directive/ngMaxlength
而ngMaxlength
只会强制执行验证。请参阅:https: //docs.angularjs.org/api/ng/directive/ngMaxlength
Advise:Just use maxlength
.
建议:只需使用maxlength
.