Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: Sum of Input values

I have a simple list of inputs bound to a list of items that display nicely. When I change a value in an input, the sum doesn't update??

Example: http://plnkr.co/edit/B7tEAsXSFvyLRmJ5xcnJ?p=preview

Html

<body ng-controller="MainCtrl">
 <div ng-repeat="item in items">
   <p><input type=text value="{{item}}"></p>
 </div>
 Total: <input type=text value="{{sum(items)}}">
</body>

Script

app.controller('MainCtrl', function($scope) {
  $scope.items = [1,2,5,7];

 $scope.sum = function(list) {
  var total=0;
  angular.forEach(list , function(item){
    total+= item;
  });
  return total;
 }

});
like image 280
Ian Vink Avatar asked Jun 08 '14 17:06

Ian Vink


Video Answer


2 Answers

Check this fiddle for implementation: http://jsfiddle.net/9tsdv/

The points to take note of:

  • Use ng-model directive with your input element to allow two-way binding between the item model and the input element
  • Since ng-repeat creates a child scope and the elements in items array are of primitive type or value type and hence they are copied by value during the first digest cycle and then further any changes made to the input fields are not reflected in the sum because modifications are bound to now present variables in ng-repeat's created child scope. (See other references on scope inheritance for more details)

HTML:

<body ng-controller="MainCtrl">
 <div ng-repeat="item in items">
   <p><input type=text ng-model="item.value"></p>
 </div>
 Total: <input type=text value="{{sum(items)}}">
</body>

Controller code:

app.controller('MainCtrl', function($scope) {
  $scope.items = [ { value: 1 }, { value: 2 }, { value: 5}, { value: 7 } ];

 $scope.sum = function(list) {
  var total=0;
  angular.forEach(list , function(item){
    total+= parseInt(item.value);
  });
  return total;
 }

});
like image 124
Robin Rizvi Avatar answered Nov 11 '22 08:11

Robin Rizvi


<body ng-controller="MainCtrl">
 <div ng-repeat="item in items">
   <p><input type=text ng-model="item"></p>
 </div>
 Total: <input type=text value="{{sum(items)}}">
</body>

You need to use ng-model...What's the difference between ng-model and ng-bind

like image 38
Srinath Avatar answered Nov 11 '22 08:11

Srinath