AngularJS→2十进制格式和用户限制选择

AngularJS -> 2-decimal format and user limit choice

本文关键字:用户 选择 格式 十进制 AngularJS      更新时间:2023-09-26

我想让number具有百分位数,并限制用户在0到1之间键入数字的选择。例如,user写入0,那么angular将转换为0000;如果用户写的是1,则为1 000。我怎样才能做到这一点?我有javascript函数的限制,但我想使它动态与angular。

    var myApp = angular.module('myApp', []);
myApp.controller('CalcCtrl', function ($scope) {
    var num = 0.0;
    $scope.qty = new Quantity();
    $scope.num = num;
  });
function Quantity(numOfPcs) {
    var qty = numOfPcs;
    this.__defineGetter__("qty", function () {
        return qty;
    });
    this.__defineSetter__("qty", function (val) {        
        val = parseFloat(val);
        qty = val;
    });
}
http://jsfiddle.net/xnehel/ur26k9cx/6/

您可以通过一些字段验证来做到这一点,参见这个plunkr。

<form name="priceForm" novalidate>
  <label>Input currency</label>
  <input type="text" name="price" ng-model="price" ng-pattern="/^'d+['.]'d{2}$/i" />
  <div ng-show="priceForm.price.$error.pattern">Invalid price</div>
</form>

如果你真正想要的是不允许用户输入任何东西,除非它符合这个模式,你需要编写一个自定义指令或使用一些库来做这件事,例如ui-mask。