2

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.

1 Answer 1

3

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 ;)

Sign up to request clarification or add additional context in comments.

2 Comments

If I change the to-precision="3", it is again formatting to 2 decimal points. based on this argument it should format the input value.
Thanks.. I found a way by using attributes["toPrecision"];

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.