我有一个数据列表,当我进行绑定(bind)时,我必须在输入的按键事件上调用一个函数(我用这个 fiddle 制作了 Angular 代码):
HTML
<div ng-app>
<div ng-controller="Ctrl">
<ul>
<li ng-repeat="item in Data">
<input ng-model="item.Value" ng-keydown="Total()" />
</li>
</ul>
Total: {{TheTotal}}
</div>
</div>
Angular
function Ctrl($scope) {
$scope.Data = [
{
Value: 1
},
{
Value: 2
}];
$scope.TheTotal= 0;
$scope.Total = function()
{
var returnValue = 0;
$scope.TheTotal = 0;
for(var i = 0; i < $scope.Data.length; i++)
{
returnValue = returnValue + parseInt($scope.Data[i].Value);
}
$scope.TheTotal = returnValue;
};
}
但是我需要的是当输入的值发生变化时,然后进行总结,但它失败了,因为总是丢失最后按下的键......有什么帮助吗?
这是 fiddle 手:Fiddler
最佳答案
不是一个独特的答案,但为了代码可重用性,我将其创建为过滤器,以便任何其他人都可以使用它
标记
<body ng-app="app">
<div ng-controller="myCtrl">
<ul>
<li ng-repeat="item in Data">
<input ng-model="item.Value"/>
</li>
</ul>
Total: {{Data | total: 'Value'}}
</div>
</body>
代码
.filter('total', function(){
return function(array, prop){
var total = 0;
angular.forEach(array, function(value){
total = total + parseInt(value[prop]);
})
return total;
}
})
关于javascript - 输入的总和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32082385/