Check out the plunker link for this directive in action. A comma is automatically added as the user types in the input, and it displays numbers with 2 decimal places.
However, there seems to be an issue where entering '2300.34' results in '230034' on the controller side after clicking 'Submit'. This discrepancy can be seen using console.log. The desired outcome is to retain the original data format on the controller end.
The code includes JavaScript and a directive:
var app = angular.module('App',[]);
app.controller('MainCtrl', function ($scope) {
$scope.getdata = function(){
console.log($scope.amount);
}
});
app.directive('format', ['$filter', function ($filter) {
return {
require: 'ngModel',
link: function (scope, elem, attrs, ctrl) {
if (!ctrl) return;
ctrl.$formatters.unshift(function (a) {
return $filter(attrs.format)(ctrl.$modelValue);
});
ctrl.$parsers.unshift(function (viewValue) {
var plainNumber = viewValue.replace(/[^\d|\-+]/g, '');
elem.val($filter('number')(plainNumber/100,2));
return plainNumber;
});
}
};
}]);
In the HTML section:
<body ng-app="App">
<div ng-controller="MainCtrl">
<input type="text" ng-model="amount" format="number" />
<input type="submit" ng-click="getdata()" />
</div>