Restrict number of decimals in html5 type=“number” input field (with Angularjs model)

后端 未结 4 2109
太阳男子
太阳男子 2021-02-13 04:18

Please find the fiddle http://jsfiddle.net/q2SgJ/5/

WANTS: {{val | number:2}} in \"input\"
4条回答
  •  死守一世寂寞
    2021-02-13 04:47

    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.

    I wrote a simple one: 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();
                }
            });
        }
    

    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.

提交回复
热议问题