5

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

});
GG.
  • 21,083
  • 14
  • 84
  • 130
Ian Vink
  • 66,960
  • 104
  • 341
  • 555

2 Answers2

10

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

});
Robin Rizvi
  • 5,113
  • 4
  • 27
  • 35
1
<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

Community
  • 1
  • 1
Srinath Mandava
  • 3,384
  • 2
  • 24
  • 37
  • Hmm. I've added a Plunker but the code doesn't 2 way bind, http://plnkr.co/edit/B7tEAsXSFvyLRmJ5xcnJ?p=preview Could you have a look? – Ian Vink Jun 08 '14 at 18:10
  • Sorry i was wrong in the sum part that we cant make a ng-model on a function and Robin is right using an array of objects..and I found the reason why my code failed and his worked here: http://stackoverflow.com/questions/15488342/binding-inputs-to-an-array-of-primitives-using-ngrepeat-uneditable-inputs – Srinath Mandava Jun 08 '14 at 18:28