Problems to sum values using Angular JS

Asked

Viewed 2,111 times

6

See the final result:

inserir a descrição da imagem aqui

<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.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>

In html

<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:  {{total}}  </small></div>
 </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}}</td>
        </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" 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="subtrairValores(); apagar(numeros)" ng-show="isNumeroSelecionado(numeros)" >Apagar</button>

</div>

<br />
  • Ever tried to use += parseFloat($scope.numero.valor)?

  • @Samirbraga, yes, I tested the overwrite values, no sum is also not subtracted

  • After analyzing your code, I have a doubt: the total, that you want, is the sum of all valor table?

  • @Samirbraga, yes, I am filling the array manually, so I want to add the total of the records that have been added or reduce if it is deleted

  • The problem is that in your job somarValores(), at the very beginning you declare the $scope.valor = 0, which prevents adding, since always before the sum, the value will be 0.

  • @Samirbraga, if I comment $Scope.total = 0; no sum, can I do it with jquery?

  • That’s exactly what I was perceiving, in fact it changes the value in Nan. I imagine yes, a little more laborious, but it is possible. I’ll be taking a look at your code, anything warning.

  • 1

    @Samirbraga, thank you for your collaboration in helping, I am very grateful for there are people like you on this site that is without doubt the best site for those who want to apender

Show 3 more comments

1 answer

4


Well, as I said, I took a look without your code and did some reworking. At least here it’s working...

Reformulations

In Javascript

1.

Remove the delete $scope.numeros of function adicionar(). I don’t know why you put it there, but it will delete the numeros after adding a value to it, then for me it made no sense, just as it is not functional. It will look like this:

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

2.

Withdraw the $scope.total = 0 from within the function somarValores(), otherwise the function will always replace the value and will not add it up. And I created a argument "number". Which must be specified in ng-click forward. Another important thing is to remove the condition:

if($scope.total == 0) $scope.total = ""; 

Because with her, you’ll be turning the total in a string and making it impossible to apply mathematical operations on it later. The result would simply look like this:

$scope.total = 0;
$scope.somarValores = function (numero) {
     $scope.total += parseFloat(numero);    
}

3.

Create the function subtrairValores(), that will delete deleted values:

$scope.subtrairValores = function () {
    $scope.numeros.forEach(function(el, i) {
        if($scope.numeros[i].selecionado){  $scope.total -= parseFloat($scope.numeros[i].valor); };
    }) 
}

.

In HTML

1.

Withdraw all ng-change, because with them when you type the value, each key the old value will be added with the new value (value with the new digit). That is, if it was 5, and you say more 1, he added the 5 + 51, getting 56.

2.

Put the function somarValores() the "add" button instead of us ng-change, without forgetting to specify the argument numero.valor, would look like this:

<button class="btn btn-primary btn-block " ng-click="adicionar(numero); somarValores(numero.valor)" ng-disabled="!numero.nJogo || !numero.valor">Adicionar</button>

3.

Specify the function subtrairValores() in the ng-click on the delete button, but before the function apagar(), so that you can subtract the values before they are deleted.

<button class="btn btn-danger btn-block " ng-click="subtrairValores(); apagar(numeros)" ng-show="isNumeroSelecionado(numeros)" >Apagar</button>

Problem of decimal places

Create a function, toFixed(), similar to that already existing in native javascript, but this will recognize if there are decimals, and if there are, will limit them to two:

function toFixed(number){
    number = parseFloat(number);
    if(number % 1 != 0){
        return parseFloat(number.toFixed(2));
    }else{
        return number;
    }
} 

So just apply this at the end of each function (sum and subtract values):

$scope.total = toFixed($scope.total); 

It would look like this - EDITED

function toFixed(number){
    number = parseFloat(number);
    if(number % 1 != 0){
        return parseFloat(number.toFixed(2));
    }else{
        return number;
    }
}
$scope.total = 0;
$scope.somarValores = function (numero) {
     $scope.total += parseFloat(numero);  
     $scope.total = toFixed($scope.total); 
}
$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); 
}

Final Result - Jsfiddle

I hope it helped.

  • 1

    +1 Great answer.

  • @Samirbraga, see in the image, can we solve the rounding of the value to two decimal places using ng-Pattern? I am very grateful that there are people like you. Immensely grateful.

  • @Techies, yes, really a great answer, more see in the image, I have a problem in rounding the value to two decimal places.

  • @itasouza, this can be solved easily, if you want I can edit the answer with a suggestion

  • @Samirbraga, if possible edit your reply please. Immensely grateful

  • In this case, ng-Pattern will only do the validation, but will still show on the screen the decimals, I will do a function in javascript to recognize if there are decimals and when there is limit them to 2. OK?

  • @itasouza, edited the answer, see if it suits you.

  • @Samirbraga, just have to thank! , about formatting the decimals did not work out much, but I will study better

  • @Samirbraga, I changed the complete code with the latest changes to stay as help for others

  • @itasouza, very good. As for the problem of decimals, here it worked right, I edited the question Xtamante as I used here. Look at "Would look like this - Edited" rsrs

  • @Samirbraga, everything perfect, everything working now! immensely grateful!

  • Full code is final in question,

  • @itasouza, very good indeed, was very happy to have helped.

  • @Samirbraga , Dear Samir Braga, if you are able to help me in this other issue, I thank you already for the help. http://answall.com/questions/106557/comond-dataos-do-angularjs-para-um-backend-em-asp-net-mvc

  • @itasouza, I think this time I can not help you, backend and Principamente Asp.net is not much with me...

Show 10 more comments

Browser other questions tagged

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