Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
938 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...