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;
}
});
Check this fiddle for implementation: http://jsfiddle.net/9tsdv/
The points to take note of:
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;
}
});
<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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With