我想将输入值0.00绑定到文本框 然后,如果我将输入更改为20然后将模糊设置为20.00
<input type="text" valid-decimal-number style="text-align:right" ng-model="Amount" ng-blur="ConvertToDecimal(Amount)">
角度脚本:
//converting value to decimal
$scope.ConvertToDecimal = function (val) {
$scope.Amount = eval(val).toFixed(2);
}
我正在使用这段代码但是,每次我写作时, 如何为此
创建自定义指令我也尝试了这样但不起作用。
<input type="text" valid-decimal-number style="text-align:right" ng-model="Amount" ng-blur="'Amount=(Amount).toFixed(2)'">
答案 0 :(得分:1)
在ng-blur
ng-blur="Amount = (Amount | number : 2 )"
演示
angular.module("app",[])
.controller("ctrl",function($scope){
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<input type="text" style="text-align:right" ng-model="Amount" ng-blur="Amount = (Amount | number : 2 )" >
</div>
答案 1 :(得分:1)
您可以将toFixed(2)
仅应用于数字
<html ng-app="myApp">
<head>
<title></title>
</head>
<body ng-controller="myCtrl">
<input type="text" valid-decimal-number style="text-align:right" ng-model="Amount" ng-blur="ConvertToDecimal()">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module("myApp", []);
app.controller('myCtrl', ['$scope', function ($scope) {
$scope.ConvertToDecimal = function (val) {
if(isNaN($scope.Amount)){
alert("given input is not a number");
return;
}
$scope.Amount = Number($scope.Amount).toFixed(2);
}
}]);
</script>
</body>
</html>