Add Values in Angular JS

0

I have 5 inputs where I enter some values, but when I try to sum the total result is not displayed in the last input . HTML:

 <label class="item item-input">
    <span class="cinza input-label">Valor 1</span>
    <input type="number" ng-model="var1"> </input></label>
    <label class="item item-input">
    <span class="cinza input-label">Valor 2</span>
    <input type="number" ng-model="var2"> </input></label>
    <label class="item item-input">
    <span class="cinza input-label">Valor 3</span>
    <input type="number" ng-model="var3"> </input></label>
    <label class="item item-input">
    <span class="cinza input-label">Valor 4</span>
    <input type="number" ng-model="var4"> </input></label>
    <label class="item item-input">
    <span class="cinza input-label">Valor 5</span>
    <input type="number" ng-model="var5"> </input></label>
    <div ng-controller="Total">
    <label class="item item-input">
    <span class="cinza input-label">Total</span>
    <input type="number" ng-model="total"> </input></label></input> 
</div>

Controller:

.controller('Total', function ($state, $scope) {

$scope.var1 = 0;
$scope.var2 = 0;
$scope.var3 = 0;
$scope.var4 = 0;
$scope.var5 = 0;

var total = $scope.var1 + $scope.var2 + $scope.var3 + $scope.var4 + $scope.var5;

$scope.total = total;

})

How do I display full value in an input?

    
asked by anonymous 16.11.2015 / 11:39

3 answers

3

It is not working because you do not call any action (function) that makes the sum.

Try the following:

At your last input put a ng-blur or #

<input type="number" ng-click="somarValores()" ng-blur="somarValores()" ng-model="var5"> </input></label>

And on your Controller:

$scope.somarValores = function(){
    $scope.total = $scope.var1 + $scope.var2 + $scope.var3 + $scope.var4 + $scope.var5;
}

Example working: link

OBS : An excerpt from your html may have problems too, I do not know how the whole structure is but I noticed that you call Controller just at the end of the html. In this way all variables declared in Controller are only "seen" in the end.

    
16.11.2015 / 11:47
4

The assertion of the other answer is true and works, but alternatively, if you want to put the value in the total property, a self-executing function can be used, such as:

$scope.total = (function(){
   $scope.var1 + $scope.var2 + $scope.var3 + $scope.var4 + $scope.var5;
})();
    
16.11.2015 / 11:51
0

If someone is still in doubt, it's resolved: link .

    
16.11.2015 / 18:35