我有一个简单的输入列表绑定到一个显示良好的项目列表。当我更改输入中的值时,总和不会更新?
示例: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>
脚本
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;
}
});
答案 0 :(得分:9)
选中这个小提琴来实施:http://jsfiddle.net/9tsdv/
需要注意的要点:
<强> 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>
控制器代码:
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;
}
});
答案 1 :(得分: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>
您需要使用ng-model ... What's the difference between ng-model and ng-bind