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;
}
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…