限制HTML5类型小数位数="数"输入字段(Angularjs模型) [英] Restrict number of decimals in html5 type="number" input field (with Angularjs model)
问题描述
请找到小提琴
http://jsfiddle.net/q2SgJ/5/
<div ng-app="">
<div ng-controller="Ctrl">
WANTS: {{val | number:2}} in "input" elelent<br>
2 decimal in input: <input ng-model='val'> <br>
2 decimal in input: <input type="number" step="0.01" ng-model='val'><br>
2 decimal in input: <input ng-model='val' value="{{val |number:2}}"> <br>
</div>
</div>
我如何限制小数点2位数的输入字段。正如例如 {{VAL |数量:2}}
工作,但不知道如何使用它来格式化连接到一个场NG-模式。我可以格式化数据/模型本身,但我有我喜欢把多余的十进制数的值,但只显示2位小数。
How can I restrict the decimal places to 2 digits in an INPUT field. As in the example {{val | number:2}}
works, but not sure how to use it to format the ng-model attached to an field. I could have formatted the data/model itself, but I have few values I like to keep the extra decimal, but only display 2 decimal.
感谢。
推荐答案
您可以写一个指令来控制这个功能。这是不是附带棱角分明,但指令可以控制的事情怎么看和工作在页面上。
You can write a directive to control this functionality. It is not something that ships with angular, but directives can control how things look and work on the page.
我写了一个简单的: http://jsfiddle.net/q2SgJ/8/
这是做的伎俩链接功能:
This is the linking function that does the trick:
link:function(scope,ele,attrs){
ele.bind('keypress',function(e){
var newVal=$(this).val()+(e.charCode!==0?String.fromCharCode(e.charCode):'');
if($(this).val().search(/(.*)\.[0-9][0-9]/)===0 && newVal.length>$(this).val().length){
e.preventDefault();
}
});
}
这工作在限制输入到小数点后2位,但输入不格式化到小数点后两位。不管怎么说,这是一个起点。我相信你可以看一下其他的例子,写自己的指令来处理这个问题,你想要的方式。关于角的事情是,它不是一个答案每个问题的框架,而是一个框架,允许您创建比单独HTML5提供额外的功能,使得它非常简单。
This works at limiting the input to 2 decimal places, but doesn't format the input to two decimal places. Anyways, it is a starting point. I am sure you can look up other examples and write your own directive to handle this the way you want. The thing about Angular is that it is not a framework with an answer to every question, but a framework that allows you to create additional functionality than what HTML5 provides alone and makes it very simple.
这篇关于限制HTML5类型小数位数=&QUOT;数&QUOT;输入字段(Angularjs模型)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!