【问题标题】:Input type number with toFixed value failing in AngularJS在AngularJS中输入带有toFixed值的类型号失败
【发布时间】:2018-11-27 18:08:12
【问题描述】:

我认为有以下要求:

  • HTML 输入 type 必须number
  • 以编程方式设置该输入的模型属性值,并带有 2 个尾随小数
  • 允许用户输入修改该值

现在,以编程方式将值设置为 1.20 以使该值显示在输入中很复杂:

  • parseFloat(1.20) 返回1.2
  • (1.20).toFixed(2) 返回一个字符串'1.20',AngularJS 在尝试设置该值时失败

有什么想法吗?

【问题讨论】:

标签: javascript html angularjs


【解决方案1】:

基于https://github.com/angular/angular.js/issues/5680#issuecomment-206325921,我做了以下事情:

(function(){
    angular.module('app')
        .directive('toFixed', [function () {
            return {
                require: '^ngModel',
                link: function(scope, element, attrs, ngModel) {
                    ngModel.$formatters.push(function(value) {
                        return parseFloat(value);
                    });
                    ngModel.$render = function() {
                        var viewValue = parseFloat(ngModel.$viewValue || 0);
                        element.val(viewValue.toFixed(2));
                    }
                }
            };
        }]);
}());

【讨论】:

    【解决方案2】:

    您可以利用 NgModel 并添加解析器或格式化程序。

    function NumberFormatter($filter){
    'ngInject';
    
    return {
        restrict: 'A',
        require: '^ngModel',
        link: function(scope, element, attrs, ngModelCtrl){
              //format text going to user (model to view)
              ngModelCtrl.$formatters.push(function(value) {
                 return $filter('number')(parseFloat(value) , 2);
              });
    
              //format text from the user (view to model)
              ngModelCtrl.$parsers.push(function(value) {
                return doParsing(value)
              });
        }
    }
    }
    

    ngModel Formatters and Parsers

    【讨论】:

    • 创建与ng-model 指令一起使用的自定义指令时,最好避免使用隔离范围。还要避免使用ng-model 属性进行双向绑定;使用单向绑定 (<) 输入,$setViewValue 输出。
    • 看起来我可以在这种情况下删除隔离范围。
    • 此解决方案没有解决在渲染到视图时使用toFixed 格式化值失败的主要问题,因为输入类型是数字,而不是字符串(toFixed 返回),否则我获取Error: [ngModel:numfmt] Expected 1.20 to be a number
    • 你能用数字输入步骤代替toFixed()吗? stackoverflow.com/questions/22641074/…
    • 我更新了答案以包含一个数字过滤器,该过滤器应始终显示两位小数。
    猜你喜欢
    • 2017-11-02
    • 2015-09-20
    • 1970-01-01
    • 2014-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    • 1970-01-01
    相关资源
    最近更新 更多