Doubt with ng-Pattern input number with 2 decimal places - Angularjs

Asked

Viewed 1,649 times

1

I am wanting to format a decimal value so that it is always sent in this formatted: 00.00, I have an example on this site http://gsferreira.com/archive/2015/02/angularjs-input-number-with-two-decimal-places/

If you type 20.10 = 20.1 (I want it to look like this 20.10) if you type 15.00 = 15 (I wanted it to stay that way 15.00)

   <input class="form-control input-sm"  type="number" name="myDecimal" placeholder="Decimal" ng-model="numero.valor" ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/" step="0.01" />
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!--inserindo a meta tag de keywords onde definimos as palavras chaves-->
    <meta name="keywords" content="" />
    <!--descrição do nosso site-->
    <meta name="description" content="Sistema" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!--inseri um logo para o meu sistema <!-https://www.iconfinder.com -->
    <link href="../Content/images/logo.png" rel="shortcut icon" />
    <title>@ViewBag.Title - Sistema</title>
    <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <!-- adicionado o css do carousel -->
    <link href="~/Content/carousel.css" rel="stylesheet">
    <script src="~/Scripts/angular.min.js"></script>
    <script src="~/Scripts/modernizr-2.6.2.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>


    <script>
        angular.module("ListaDados", []);
        angular.module("ListaDados").controller("ListaDadosCtrl", function ($scope) {
            $scope.app = "Dados que serão inseridos";

            $scope.numeros = [];

            $scope.adicionar = function (numero) {
               $scope.numeros.push(angular.copy(numero));
               delete $scope.numero;
            };

            $scope.apagar = function (numeros) {
               $scope.numeros = numeros.filter(function (numero) {
                    if (!numero.selecionado) return numero;
                });
            };


            $scope.isNumeroSelecionado = function (numeros) {
                return numeros.some(function(numero){
                  return numero.selecionado;
                });
            };



        });
    </script>


</head>




<div class="container droppedHover">
    <div class="row">
        <div class="input-prepend input-append">
            <input class="form-control input-sm " onkeyup="somenteNumeros(this);" placeholder="número" maxlength="4"  type="text"  ng-model="numero.nJogo" />
            <input class="form-control input-sm"  type="number" name="myDecimal" placeholder="Decimal" ng-model="numero.valor" ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/" step="0.01" />
        </div>
    </div>
    <br/>
    <button class="btn btn-primary btn-block " ng-click="adicionar(numero)" ng-disabled="!numero.nJogo || !numero.valor">Adicionar</button>
    <button class="btn btn-danger btn-block " ng-click="apagar(numeros)" ng-show="isNumeroSelecionado(numeros)" >Apagar</button>

</div>
  • I don’t quite understand your question, do you want when the value is passed from the model to the view that it is displayed with two decimal places? What if the user decides to edit the field that contains the format value and type one with only one decimal place? What should happen? If you can explain better what logic you want in this input maybe it will be easier for people to help you.

  • I already have a solution, posted the complete answer.

2 answers

1

ng-Pattern is only used for validation, in addition you will need to create a directive that requires ngModel and include a $parse to do this job.

In short do something like:

angular.module('seuApp').directive('suaDirective', function() {
  return {
require: 'ngModel',
link: function(scope, element, attrs, ngModelController) {
  ngModelController.$parsers.push(function(data) {
    return parseFloat(data).toFixed(2); //converted
  });
}
  }
});

Then only include in HTML.

  • if I can’t make your example, I added the full code to my question, would it be possible for you to use it to build this example of yours so that it is easier to understand? thanks

  • I already have a solution, posted the full answer. I appreciate the help!

  • hello, glad you could. I came back today from the holiday lol

1


The simplest solution for formatting decimals:

<!-- adicionado para formatar em moeda corrente -->
<script src="~/Scripts/angular-locale_pt-br.js"></script> 

inserir a descrição da imagem aqui

The Complete Code looks like this:

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!--inserindo a meta tag de keywords onde definimos as palavras chaves-->
    <meta name="keywords" content="" />
    <!--descrição do nosso site-->
    <meta name="description" content="Sistema" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!--inseri um logo para o meu sistema <!-https://www.iconfinder.com -->
    <link href="../Content/images/logo.png" rel="shortcut icon" />
    <title>@ViewBag.Title - Sistema</title>
    <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <!-- adicionado o css do carousel -->
    <link href="~/Content/carousel.css" rel="stylesheet">
    <script src="~/Scripts/angular.min.js"></script>
    <!-- adicionado para formatar em moeda corrente -->
    <script src="~/Scripts/angular-locale_pt-br.js"></script> 
    <script src="~/Scripts/modernizr-2.6.2.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>



    <script>
        angular.module("ListaDados", []);
        angular.module("ListaDados").controller("ListaDadosCtrl", function ($scope) {
            $scope.app = "Dados que serão inseridos";

            $scope.numeros = [];
            $scope.total = 0;


            $scope.adicionar = function (numero) {
                $scope.numeros.push(angular.copy(numero));
                $scope.total += parseFloat(numero.valor);
                $scope.total = toFixed($scope.total);
                delete $scope.numero; //aqui eu limpo os campos dos inputs apos adicionar
            };

            $scope.apagar = function (numeros) {
                $scope.numeros = numeros.filter(function (numero) {
                    if (!numero.selecionado) return numero;
                });
            };


            $scope.isNumeroSelecionado = function (numeros) {
                return numeros.some(function(numero){
                  return numero.selecionado;
                });
            };

            //função para subtrair os valores
            $scope.subtrairValores = function () {
                $scope.numeros.forEach(function (el, i) {
                    if ($scope.numeros[i].selecionado) { $scope.total -= parseFloat($scope.numeros[i].valor); };
                })
                $scope.total = toFixed($scope.total);
            };


        });
    </script>

    <!-- formatar casas decimais-->
    <script>
        function toFixed(number) {
            number = parseFloat(number);
            if (number % 1 != 0) {
                return parseFloat(number.toFixed(2));
            } else {
                return number;
            }
        }

    </script>



</head>




<br />
<div class="panel panel-default">
    <div class="panel-heading"><small> Vendedor: @Session["nome"]</small> </div>
    <div class="panel-heading"><small> Jogo: @Session["descricao_modalidade"] </small></div>
    <div class="panel-heading"><small> Limite: @Session["limite_aceite"] </small></div>
    <div class="panel-heading"><small> Extração: @Session["descricao_estracao"] </small></div>
    <div class="panel-heading"><small> Fechamento: @Session["hora_fechamento"] - Dia: @Session["dia_da_semana"] </small></div>
    <div class="panel-heading"><small> Valor Total Jogo:  {{total  | currency}}  </small></div> <!-- formatar o valor com casas decimais-->
 </div>


<table class="table table-bordered" ng-show="numeros.length > 0" >
    <thead>
        <tr>
            <th>X</th>
            <th>Número: </th>
            <th>Valor: </th>
        </tr>
    </thead>
    <tbody>
        <tr ng-class="{'selecionado negrito':numero.selecionado}"  ng-repeat=" numero in numeros" >
            <td><input type="checkbox" ng-model="numero.selecionado" /></td>
            <td>{{numero.nJogo}}</td>
            <td>{{numero.valor | currency }}</td> <!-- formatar o valor com casas decimais-->
        </tr>
    </tbody>
</table>


@*<input class="form-control input-sm" onkeyup="somenteNumeros(this);" placeholder="valor" maxlength="5" type="text" ng-model="numero.valor" />*@

<div class="container droppedHover">
    <div class="row">
        <div class="input-prepend input-append">
            <input class="form-control input-sm " onkeyup="somenteNumeros(this);" placeholder="número" maxlength="4"  type="text"  ng-model="numero.nJogo" />
            <input class="form-control input-sm"  type="number" name="myDecimal" ng-change="somarValores()"  placeholder="Decimal" ng-model="numero.valor" />
        </div>
    </div>
    <br/>
    <button class="btn btn-primary btn-block " ng-click="adicionar(numero)" ng-disabled="!numero.nJogo || !numero.valor">Adicionar</button>
    <button class="btn btn-danger btn-block " ng-click="subtrairValores(); apagar(numeros)" ng-show="isNumeroSelecionado(numeros)" >Apagar</button>

</div>

<br />

Browser other questions tagged

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