1 decimal formatted value in ngModel

Asked

Viewed 3,920 times

1

I have the following object:

dadosAnv = { horas_cel: 1950.0 }

It turns out that when I edit this value, it appears in the input only 1950. I’d like to keep the .0 value, but I have no idea how to format this value through a directive for example.

1 answer

1


EDITED: As AP edit, I created a directive that formats the value as needed. I put two options, using the toFixed() of JavaScript or the $filter of Angular.

Use the filter number.

angular.module('myApp', [])
  .controller('myController', ['$scope',
    function($scope) {
      $scope.val = 1234.0;
    }
  ]);

angular.module('myApp')
  .directive('myDirective', function($filter) {
    return {
      require: 'ngModel',
      link: function(scope, element, attrs, ngModelController) {
        ngModelController.$formatters.push(function(data) {
          return $filter('number')(data, 2);
          //return Math.round(data).toFixed(2);
        });
      }
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myController">
  <label>Informe o número:
    <input type="text" ng-model='val' my-directive>
  </label>
  <br>Formatação padrão: <span id='number-default'>{{val | number}}</span>
  <br>Sem casas decimais: <span>{{val | number:0}}</span>
  <br>Com 2 casas decimais: <span>{{val | number:2}}</span>
</div>

  • Hello Pedro Camara Jurnior, the number filter does not serve in my case because it does not format the <input> that is my problem. I think it would have to be a directive to do this, but as a beginner I only know how to do the formatting at the time of typing. A simple toFixed(1) would solve!

  • Got it now, take a look at the edited answer,

  • That’s right, vlw Pedro!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.