我在将表单数据字段显示为2个小数位置时存在问题。我将可变$Scope.theItem.Charge
设置为十进制位置:
$scope.theItem.charge = parseFloat(10 * 2).toFixed(2);
i然后在这样的可编辑表单字段中显示此数据:
<input type="text" name="charge" id="charge" ng-model="theItem.charge">
这可以正常工作并显示结果,在这种情况下为20.00
。但是,因为我们说这是用户能够输入任何文本的输入类型,而不仅仅是数字。我希望只能做到这一点:
<input type="number" name="charge" id="charge" ng-model="theItem.charge" step="0.01">
,但这返回以下错误:
angular.min.js:119错误:[ngmodel:numfmt]
http://errors.angularjs.org/1.5.9/ngmodel/numfmt?p0=25.00
在Angular.min.js:6
在数组。(Angular.min.js:182)
在Angular.min.js:293
在M。$ digest(Angular.min.js:144)
在m。$ appl(angular.min.js:147)
在L(Angular.min.js:98)
在D(Angular.min.js:103)
在XMLHTTPREQUEST.W.ONLOAD(Angular.min.js:104)
有人对如何解决这个问题有任何想法吗?我尝试使用上面链接中所述的角指令,但这对我的方案不起作用。
我们使用ng-currency处理此问题。这似乎是处理输入字段中小数的最稳定方法。ng-currency
确实以一种很好的方式验证您的ng-model
。因此,您不再需要与分数或错误的用户输入数据进行战斗。请检查此演示PLNKR 。
angularjs应用程序
var app = angular.module('plunker', ['ng-currency']);
app.controller('ApplicationController', function($scope) {
$scope.amount = '0.203';
});
查看
<div class="container" ng-controller="ApplicationController">
<div class="row">
<input type="text"
ng-model="amount"
currency-symbol=""
ng-currency
fraction="2" />
</div>
</div>
->演示PLNKR
错误:ngmodel:numfmt模型不是类型number
您应该解析范围。
$scope.theItem.charge = parseFloat(parseFloat(10 * 2).toFixed(2));
是的,这很难...:)
您还可以编写用于解析字符串的指令:
directive('parseFloat', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
ngModel.$parsers.push(function(value) {
return '' + value;
});
ngModel.$formatters.push(function(value) {
return parseFloat(value);
});
}
};
});
,只需在输入字段上使用此指令:
<input type="number" name="charge" id="charge" ng-model="theItem.charge" step="0.01" parseFloat>