I have 2 inputs that only accepts positive floats with 2 decimals (other characters should be removed by change()
function).
When the value of an input is changed, the value of the other input is automatically changed too.
Issue #1 - Main problem
My regex does not block beyond 2 decimals and allow severals .
(eg: 12.345.67 sadly works).
Issue #2
Forbidden chars are not properly removed on the call of change()
. I get
Error: $scope.uc.replace is not a function
This occurs because replace()
only works on strings, and math operators (+
, -
, *
, /
) only works on numbers. I need to use both, how to deal with it?
Here is my code, you can use this JSFiddle if you want to try it yourself.
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>