Freddy Castelblanco
Freddy Castelblanco

Reputation: 83

Sum array of inputs

I have a list of data which when I make the bind I have to call a funcion on keypress event of input (I made my code in angular with this fiddle):

HTML

<div ng-app>
  <div ng-controller="Ctrl">
    <ul>
        <li ng-repeat="item in Data">
            <input ng-model="item.Value" ng-keydown="Total()" />

            </li>
        </ul>
      Total: {{TheTotal}}
  </div>
</div>

ANGULAR

function Ctrl($scope) {
  $scope.Data = [
    {
        Value: 1
    },
    {
        Value: 2
    }];
    $scope.TheTotal= 0;
    $scope.Total = function()
    {
        var returnValue = 0;
        $scope.TheTotal  = 0;       

        for(var i = 0; i < $scope.Data.length; i++)
        {
            returnValue = returnValue + parseInt($scope.Data[i].Value);                  
        }

        $scope.TheTotal =  returnValue;        
    };
}

But what I need is when the value of input changes, then makes the summatory but it is failing because always lost the last key pressed ... Any help ??

Here is the fiddler: Fiddler

Upvotes: 0

Views: 140

Answers (3)

Pankaj Parkar
Pankaj Parkar

Reputation: 136184

Not an unique answer but for code reusability I'll create it as filter so that any other can take use of it

Markup

<body ng-app="app">
  <div ng-controller="myCtrl">
    <ul>
        <li ng-repeat="item in Data">
            <input ng-model="item.Value"/>
        </li>
        </ul>
      Total: {{Data | total: 'Value'}}
  </div>

</body>

Code

.filter('total', function(){
  return function(array, prop){
    var total = 0;
    angular.forEach(array, function(value){
      total = total + parseInt(value[prop]);
    })
    return total;
  }
})

Demo Plunkr

Upvotes: 2

Kevin B
Kevin B

Reputation: 95062

The event you are using to update the total is triggering before the value of the input has actually changed. You should instead either use the keyup event, or the change event.

http://jsfiddle.net/ygkhh5q5/12/

<div ng-app>
  <div ng-controller="Ctrl">
    <ul>
        <li ng-repeat="item in Data">
            <input ng-model="item.Value" ng-change="Total()" />

            </li>
        </ul>
      Total: {{TheTotal}}
  </div>
</div>

Upvotes: 0

Puzzle84
Puzzle84

Reputation: 540

As per This thread here

the following will do the trick: http://jsfiddle.net/ygkhh5q5/6/

<div ng-app>
  <div ng-controller="Ctrl">
    <ul>
        <li ng-repeat="item in Data">
            <input ng-model="item.Value" />

            </li>
        </ul>
      Total: {{sum(Data)}}
  </div>
</div>

function Ctrl($scope) {
  $scope.Data = [
    {
        Value: 1
    },
    {
        Value: 2
    }];
    $scope.sum = function(list) {
      var total=0;
      angular.forEach(list , function(item){
        total+= parseInt(item.Value);
      });
      return total;
     }
}

Upvotes: 0

Related Questions