Reputation: 163
I have some 10 textboxes and if user enters 10.3691 then it should be changed to 10.37
<input ng-model='data.value1' ng-blur="formatDecimals1()">
<input ng-model='data.value2' ng-blur="formatDecimals2()">
......
In controller,
$scope.formatDecimals1 = function() {
$scope.data.value1= Number($scope.data.value1).toFixed($scope.data.value1Points);
}
$scope.formatDecimals2 = function() {
$scope.data.value2= Number($scope.data.value2).toFixed($scope.data.value2Points);
}
I feel this is not a right way... any other solution to achieve this. Or, how we can have single common function to format all textbox inputs.
Upvotes: 2
Views: 4498
Reputation: 19618
You could write a custom directive, something like:
angular.module('app', []).
directive('toPrecision', function(){
return {
replace: false,
restrict: 'A',
link: function(scope, element) {
var e = angular.element(element);
e.on('keyup', function(){
var n = parseFloat(e.val());
if (parseInt(n, 10) !== n && String(n).split('.')[1].length > 2) {
e.val(n.toFixed(2));
}
});
}
}
});
then in the markup:
<div ng-app="app">
<input type="number" to-precision="2" />
</div>
You can try the working code here: http://jsfiddle.net/ctgxd4va/
ps. I wrote it in 2 minutes, it's far from perfection... but it should give you an idea ;)
Upvotes: 3