1

What is the correct way, in angularjs, to format an input field value base on whether or not the input has focus?

I have an input that displays numbers and I want to show values rounded to 2 decimal places, but also want that when the user goes to edit the field the full value will be shown and available to edit.

i.e.

a - I have a model with the value 1200.0166667 stored

b - when the bound input field doesn't have focus I want to display 1200.017

c - but when the input has focus I want to display the full value 1200.0166667

what is the correct way of doing this?

Pedro Figueiredo
  • 2,146
  • 1
  • 14
  • 15

2 Answers2

0

Check this demo code

You can use ng-focus and ng-blur and make it happen

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  $scope.num = 1200.017;

  $scope.onFocus = function(){
    $scope.num = 1200.0166667;
  }

  $scope.onBlur = function(){
    $scope.num = 1200.017;
  }
});

in js file:

<input ng-focus="onFocus()" ng-model="num" ng-blur="onBlur()"/>

This is very crude example. You can get the idea and put necessary logic accordingly.

Shashank Vivek
  • 16,888
  • 8
  • 62
  • 104
  • I didn't want to change the model value. have a lot of inputs bound that need to have this formatting solution. I would prefer a fast directive. – Pedro Figueiredo Mar 02 '19 at 18:39
0

After doing some code for this problem I've come out with this directive

var myApp = angular.module('myApp', []);
 
myApp.controller('MyCtrl', function($scope) {
  $scope.numberVal = 200.0 / 3.0;
});

myApp.directive('myNumber', function($filter, $browser) {
    return {
        require: 'ngModel',
        link: function($scope, $element, $attrs, ngModelCtrl) {
            
            $element.bind('blur', function (e) {
                ngModelCtrl.$render();
            });
            
            $element.bind('focus', function(e) {
              ngModelCtrl.$render();
            });
            
            ngModelCtrl.$render = function() {
                if ($element.is(":focus"))
                 $element.val(ngModelCtrl.$viewValue);
                else {
                 var val = ngModelCtrl.$viewValue;
                  if (isNaN(val)) $element.val(val);
                  else $element.val(Math.round(val * 100) / 100);
                }
            }
        }
        
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-App="myApp" ng-controller="MyCtrl">
    <div>Raw Value: {{numberVal}}</div>
    <input type='text' my-number ng-model="numberVal"/>
</div>
Pedro Figueiredo
  • 2,146
  • 1
  • 14
  • 15