我有2個輸入,只接受帶2位小數的正浮點數(其他字符應該被change()
函數刪除)。在兩個輸入之間自動更改控件
當輸入值改變時,另一個輸入的值也會自動改變。
問題#1 - 主要問題
我的正則表達式不會阻止超過2位小數,並允許severals .
(如:12.345.67黯然工作)。
問題2:
禁止字符不正確對change()
的通話中移除。我得到
Error: $scope.uc.replace is not a function
這是因爲replace()
僅適用於字符串和數學運算符(+
,-
,*
,/
)僅適用於數字。我需要同時使用,如何處理它?
這是我的代碼,如果你想親自嘗試,可以使用this JSFiddle。
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.coeff = 0.5;
$scope.uf = '25';
$scope.uc = '';
$scope.change = function(type) {
console.log(type, "changes!");
$scope.uf = $scope.uf.replace(',', '.');
$scope.uf = $scope.uf.replace(/[^\d.-]/g, '');
$scope.uc = $scope.uc.replace(',', '.');
$scope.uc = $scope.uc.replace(/[^\d.-]/g, '');
if(type == 'uf') {
$scope.uc = $scope.uf * $scope.coeff;
} else if(type == 'uc') {
$scope.uf = $scope.uc/$scope.coeff;
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<input type="text" ng-model="uf" ng-change="change('uf')"/>
<input type="text" ng-model="uc" ng-change="change('uc')"/>
</div>
'type =「number」'不允許輸入非數字字符。這裏我想阻止用戶輸入非浮點數... :) – Mistalis