Auto-changes between 2 inputs with controls
http://stackoverflow.com/questions/38478593/auto-changes-between-2-inputs-with-controls
by Mistalis
HTML
<script src="http://code.angularjs.org/angular-1.0.1.js"></script>
<div ng-controller="MyCtrl">
<input type="text" ng-model="uf" ng-change="change('uf')" float-only/>
<input type="text" ng-model="uc" ng-change="change('uc')" float-only/>
</div>
JavaScript
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!");
if(type == 'uf') {
$scope.uc = +parseFloat($scope.uf * $scope.coeff).toFixed(2);
} else if(type == 'uc') {
+parseFloat($scope.uf = $scope.uc / $scope.coeff).toFixed(2);
}
}
}
angular.module('myApp').directive('floatOnly', function() {
return {
require: 'ngModel',
restrict: 'A',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function(inputValue) {
if(inputValue === undefined) return '';
cleanInputValue = inputValue.replace(',', '.')
.replace(/[^\d.]/g, '')
.replace(/\./, "x")
.replace(/\./g, "")
.replace(/x/, ".");
if(cleanInputValue != inputValue) {
modelCtrl.$setViewValue(cleanInputValue);
modelCtrl.$render();
}
return cleanInputValue;
});
}
}
});