Problems to add values using Angular JS

6

See the final result:

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

No 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 />
    
asked by anonymous 31.12.2015 / 14:43

1 answer

4

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

Reformulations

In Javascript

1.

Remove the delete $scope.numeros from the adicionar() function. I do not know why you put it there, but it will delete numeros after adding a value to it, so it did not make sense to me, just as it is not functional. It will look like this:

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

2.

Remove the $scope.total = 0 from within the somarValores() function, otherwise the function will always override the value and not add up. And I created a% with% "number". Which will have to be specified in the argument more ahead. Another important thing is to remove the condition:

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

Because with it, you will be transforming ng-click into a string and making it impossible to apply mathematical operations on it later. The result would look like this:

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

3.

Create the total function, which will delete the deleted values:

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

.

No HTML

1.

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

2.

Putting the 56 function on the "add" button instead of the somarValores() , without forgetting to specify the ng-change argument, 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 numero.valor in the subtrairValores() on the delete button, but before the ng-click function, so that the values can be subtracted before they are deleted.

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

Decimal point problem

Create a function, apagar() , similar to the existing one in the native javascript, but it will recognize if there are decimal places, and if there are, 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 to 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 Score - JsFiddle

I hope you have helped.

    
01.01.2016 / 00:02