嗨,我有像这样的动态字段
<tr ng-repeat="category in staff_categories">
<td>{{ category.name }}</td>
<td><input type="text" ng-model="category.permanent"></td>
<td><input type="text" ng-model="category.temp"></td>
</tr>
按预期正常工作。它根据staff_categories进行迭代。 现在我想要用户输入的category.permanent和category.temp值的总计,并将其放在文本框中。请帮助
Total permanent:<input type="text">
Total Temp:<input type="text">
答案 0 :(得分:2)
在将被调用的控制器中创建一个函数,并更新包含这些值的总和的范围变量。
<tr ng-repeat="category in staff_categories">
<td>{{ category.name }}</td>
<td><input type="text" ng-model="category.permanent" ng-change="updatePermanentTotal()"></td>
<td><input type="text" ng-model="category.temp" ng-change="updateTemp()"></td>
</tr>
控制器代码
$scope.permanentTotal = 0.0;
$scope.tempTotal = 0.0;
$scope.updatePermanentTotal = function(){
$scope.permanentTotal = 0.0;
angular.forEach($scope.staff_categories, function(value, key){
if(!isNaN(parseInt(value.temp)){
$scope.tempTotal = $scope.tempTotal + parseInt(value.temp);
}
})
}
$scope.updateTemp = function(){
$scope.tempTotal = 0.0;
angular.forEach($scope.staff_categories, function(value, key){
$scope.tempTotal = $scope.tempTotal + parseInt(value.temp);
})
}
并将这两个总变量绑定到两个输入,如下所示。
Total permanent:<input type="text" ng-model="permanentTotal">
Total Temp:<input type="text" ng-model="tempTotal">
答案 1 :(得分:0)
您可以使用一个函数并将参数传递给它。
显示总数
<p> Permanent Total: {{ getTotal(permanent) }}</p>
<p> Temp Total: {{ getTotal(temp) }}</p>
在控制器
中$scope.getTotal = function(category){
var total = 0;
if(category == 'permanent'){
angular.forEach(staff_categories, function(item){
total = total + parseInt(item.temp);
});
} else {
angular.forEach(staff_categories, function(item){
total = total + parseInt(item.permanent);
});
}
return total;
}