AngularJS:输入值的总和 [英] AngularJS: Sum of Input values
本文介绍了AngularJS:输入值的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个简单的输入列表,绑定到一个显示效果很好的项目列表.当我更改输入中的值时,总和不会更新?
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??
示例: 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;
}
});
推荐答案
检查此提琴是否实现: http://jsfiddle.net/9tsdv/
Check this fiddle for implementation: http://jsfiddle.net/9tsdv/
要注意的要点:
- 在输入元素中使用ng-model指令,以实现项目模型和输入元素之间的双向绑定
- 由于ng-repeat创建了一个子作用域,并且items数组中的元素属于原始类型或值类型,因此它们在第一个摘要周期中按值进行复制,然后对输入字段所做的任何更改都不会反映在总和,因为修改已绑定到ng-repeat的已创建子范围中的变量. (有关更多信息,请参见有关范围继承的其他参考)
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;
}
});
这篇关于AngularJS:输入值的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文