angular,使用directive实现,将input的数字保留两位小数,不足两位补0.

https://www.oschina.net/code/snippet_929096_53265

angular.module('app').directive('numFormat',function() {
    return {
        scope:{
            model : '=ngModel'
        },
        link: function(scope, elm, attrs, ctrl) {
             
            function format(){
                if(isNaN(scope.model) || scope.model == ""){
                    scope.model = "0.00";
                }else{
                    //最多保留两位小数
                    var f = parseFloat(scope.model);
                    var f = Math.round(scope.model*100)/100;
                    var s = f.toString();
                    var rs = s.indexOf('.');
                    if(rs < 0){
                        s = s + ".00";
                    }else{
                        while(s.length <= rs + 2){s += '0';}
                    }
                    scope.model = s;
                }
            }
            format();//初始化
            $(elm).bind("blur",format);//jq方式绑定事件
        }
    };
});


你可能感兴趣的:(AngularJs)