AngularJS:未聚焦时在输入中显示格式化的模型值

AngularJS: Display formatted model value in input when not focussed

本文关键字:显示格式 显示 格式化 模型 输入 聚焦 AngularJS      更新时间:2023-09-26

假设我有一个输入,如下所示:

<input type="text" ng-model="myVariable">

当前值为 600.23。$scope.myVariable 的值应始终为 600.23(除非用户更改值(我希望输入在输入没有焦点时显示 $600.23,但是当使用提供输入焦点时,我希望它切换到未格式化的 ng-model 值 600.23 供用户编辑。用户完成编辑并移走焦点后,我希望显示的值再次采用货币格式。基本上类似于电子表格应用程序中格式化单元格的工作方式。为了使问题简单,请忽略输入验证的需要。

这可以用jQuery相当容易地完成,但是可以用纯AngularJS做到这一点吗?

您可以使用ngBlur ang ngFocus来切换值。创建函数,该函数将添加 $ 并在 ngBlur 上触发它,另一个用于删除它。

这是我创建的解决方案,它依赖于jQuery(更糟糕的是,eval!(:

angular.module('app', [])
.directive('displayFormat', function () {
    return function (scope, element, attr) {
        $(element).focus(function () {
            $(this).val(eval('scope.' + $(this).attr('ng-model')));
        });
        $(element).blur(function () {
            var modelValue = parseFloat(eval('scope.' + $(this).attr('ng-model')));
            if (attr["displayFormat"] == 'currency') $(this).val('$' + modelValue.numberFormat(2));
            if (attr["displayFormat"] == 'percentage') $(this).val((modelValue * 100) + '%');
        });
    };
});
Number.prototype.numberFormat = function (decimals, dec_point, thousands_sep) {
    dec_point = typeof dec_point !== 'undefined' ? dec_point : '.';
    thousands_sep = typeof thousands_sep !== 'undefined' ? thousands_sep : ',';
    var parts = this.toFixed(decimals).toString().split('.');
    parts[0] = parts[0].replace(/'B(?=('d{3})+(?!'d))/g, thousands_sep);
    return parts.join(dec_point);
}

然后在控制器中:

$scope.$watch(function () {
    $('input').not(':focus').blur();
});

然后是输入字段:

<input type="text" ng-model="myVariable" display-format="currency">

(在我的实际应用程序中,除了货币之外,我将实现其他显示格式选项(

不过,我真的很想有一个非jQuery解决方案。