I'm trying to make input for currency where thousand are separate with "." and decimal are separate with "," example: 1.000,00. And that is how it should be displayed in input field but model should be like 1000.00. If we have model value it should be displayed as 1.000,00,and if there are not it could stay empty So far I have something like this:
// Code goes here
var app = angular.module("myApp", []);
app.controller("myController", function ($scope) {
$scope.amount = 12548.12
});
app.directive('smartFloat', function () {
return {
controller($scope) {
},
require: 'ngModel',
restrict: 'A',
link: function (scope, element, attr, ngModel) {
function inputValue() {
var inputVal = element.val();
var res;
//clearing left side zeros
while (inputVal.charAt(0) == '0') {
inputVal = inputVal.substr(1);
}
inputVal = inputVal.replace(/[^\d.\',']/g, '');
var point = inputVal.indexOf(",");
if (point >= 0) {
inputVal = inputVal.slice(0, point + 3);
}
var decimalSplit = inputVal.split(",");
var intPart = decimalSplit[0];
var decPart = decimalSplit[1];
intPart = intPart.replace(/[^\d]/g, '');
if (intPart.length > 3) {
var intDiv = Math.floor(intPart.length / 3);
while (intDiv > 0) {
var lastComma = intPart.indexOf(".");
if (lastComma < 0) {
lastComma = intPart.length;
}
if (lastComma - 3 > 0) {
intPart = intPart.slice(0, lastComma - 3) + "." + intPart.slice(lastComma - 3);
}
intDiv--;
}
}
if (decPart === undefined) {
decPart = "";
}
else {
decPart = "," + decPart;
}
if (intPart == "" && decPart != "") {
intPart = 0;
}
if (intPart == "" && decPart == "") {
res = null;
} else {
res = intPart + decPart;
}
if (res != inputValue) {
ngModel.$setViewValue(res);
ngModel.$render();
}
return res
}
//from model to view
ngModel.$parsers.push(inputValue);
ngModel.$formatters.push(function(val){
return val
});
}
};
})
<!DOCTYPE html>
<html>
<head>
<script data-require="angularjs@1.6.1" data-semver="1.6.1" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-app="myApp">
<div ng-controller="myController">
<input type="text" class="form-control" id="inputAmount" name="inputAmount" placeholder="Amount" ng-model="amount" smart-float />
<span class="help-block" ng-show="myForm.inputAmount.$error.float">
Invalid Amount!
</span>
{{amount}}
</div>
</div>
</body>
</html>