输入type = "number"时,Angular指令不能工作

angular directive does not work with input type = "number"

本文关键字:quot Angular 指令 工作 不能 number type 输入      更新时间:2023-09-26

以下代码仅在输入类型为文本时有效,当输入类型为数字时不起作用

<div ng-app="myApp" ng-controller="myCtrl as model">
 <input type="text"  ng-model="cero" ng-decimal   >   
</div> 

angular
    .module("myApp",[])
    .controller('myCtrl', function($scope){
        var model=this;
    })
    .directive('ngDecimal', function ($parse) {
        var linkFunction =function(scope, element, attrs){     
            element.bind("keypress", function(event) {
                if(event.which === 13) {    
                    scope.$apply(function(){
                        scope.$eval(attrs.format, {'event': event});
                        if(scope.cero===undefined || scope.cero===''){
                            scope.cero="0.", 
                            event.preventDefault();
                        }else{
                        }
                    });
                }
            });
        };
        return{
            restrict : 'A',
            scope:{
                cero: '=ngModel'
            },
            link: linkFunction
        }
    });

我需要帮助的是改变类型到数字,仍然使代码工作。代码也在CodePen上。

更新笔:http://codepen.io/anon/pen/QKOVkP?editors=1011

与number一起工作,限制是不能赋值

scope.cero = "0." // string value

type="number",所以用你想要分配的最小数字替换它,可能是

scope.cero = parseFloat("0.01")  // parseFloat("0.") won't work

在else条件中加上这个

scope.cero = parseFloat(scope.cero).toFixed(2);

将字符串转换为十进制

下面是代码:working code