AngularJS在数字输入字段中显示2个小数点数字

Jan*_*ney 5 javascript input angularjs

我在将表单数据字段显示为小数点后两位时遇到问题。我将变量设置$Scope.theItem.Charge为小数点后两位:

\n\n
$scope.theItem.charge = parseFloat(10 * 2).toFixed(2);\n
Run Code Online (Sandbox Code Playgroud)\n\n

然后,我将这些数据显示在可编辑的表单字段中,如下所示:

\n\n
<input type="text" name="charge" id="charge" ng-model="theItem.charge">\n
Run Code Online (Sandbox Code Playgroud)\n\n

这可以正常工作并显示结果,在本例中是20.00。\n但是,因为我们说这是“文本”输入类型,所以用户可以在字段中输入任何文本,而不仅仅是数字。我\xe2\x80\x99d 希望简单地这样做:

\n\n
<input type="number" name="charge" id="charge" ng-model="theItem.charge" step="0.01">\n
Run Code Online (Sandbox Code Playgroud)\n\n

但这会返回以下错误:

\n\n
\n

angular.min.js:119 错误: [ngModel:numfmt]
\n http://errors.angularjs.org/1.5.9/ngModel/numfmt?p0=25.00
\n 在 angular.min.js:6
\n在大批。(angular.min.js:182)
\n 在 angular.min.js:293
\n 在 m.$digest (angular.min.js:144)
\n 在 m.$apply (angular.min.js:147 )
\n 在 l (Angular.min.js:98)
\n 在 D (Angular.min.js:103)
\n 在 XMLHttpRequest.w.onload (Angular.min.js:104)

\n
\n\n

有谁对如何解决这个问题有任何想法?我\xe2\x80\x99ve 尝试使用上面链接中描述的角度指令,但这不适用于我的场景。

\n

lin*_*lin 7

我们使用ng-currency来处理这个问题。这似乎是处理输入字段中小数的最稳定的方法。确实以一种很好的方式ng-currency验证和标准化你的。ng-model因此,您不再需要与分数或错误的用户输入数据作斗争。请检查这个演示 plnkr

AngularJS 应用程序

var app = angular.module('plunker', ['ng-currency']);

app.controller('ApplicationController', function($scope) {
  $scope.amount = '0.203';
});
Run Code Online (Sandbox Code Playgroud)

看法

<div class="container" ng-controller="ApplicationController">
    <div class="row">
      <input type="text" 
             ng-model="amount"
             currency-symbol=""
             ng-currency 
             fraction="2" />
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

-->演示 plnkr