我有一个包含列的表格,我需要在其中计算表格更改事件中其他单元格的值。我想用 ng-change 来做这件事,所以可以立即看到变化。问题是,我不知道如何正确使用 ng-model - 如果在一行中使用,它将在所有行中使用,所以每一行都被重新计算,这是我不想要的。我只想一次更新一行。
Angular 需要 ng-model,其中使用了 ng-change。表格有多行时如何正确使用 ng-change?
我可以使用 jQuery onchange 事件来做到这一点,但我已经有了 HTML 上的 Controller ,所以我想用 Angular 来做所有事情。
其中一行的示例:
<tr class="jtable-data-row jtable-row-even"
data-record-key="110000001"><td>110000001</td>
<td><input type="text"
ng-change="RecalculateValues($event);" ng-model="Quantity" value="1"></td>
<td><input type="text"
ng-change="RecalculateValues($event);" ng-model="Bruto" value="7.15"></td>
<td><input type="text"
ng-change="RecalculateValues($event);" ng-model="Neto" class="cellContent" class="cellContent" value="17"></td>
</tr>
编辑:
Plunker这里显示了我的问题 - 尽管 ng-change 事件已连接到输入值,但单元格未更新。
最佳答案
你做错了。
例子:
<tr>
<td>{{total}}</td>
<td>
<input type="text" ng-change="calculate()" ng-model="quantity">
</td>
<td>
<input type="text" ng-change="calculate()" ng-model="bruto">
</td>
</tr>
Controller :
$scope.quantity = 1;
$scope.bruto = 7.5;
$scope.total = 0;
$scope.calculate = function() {
$scope.total = $scope.quantity * $scope.bruto;
}
$scope.calculate();
如果您有多个表格行,您将需要一组对象,每个对象包含一个数量、bruto 和一个总数。
<tr ng-repeat="n in valuesArray">
<td>{{n.total}}</td>
<td>
<input type="text" ng-change="calculate($index)" ng-model="n.quantity">
</td>
<td>
<input type="text" ng-change="calculate($index)" ng-model="n.bruto">
</td>
</tr>
Controller :
$scope.valuesArray = [
{quantity: 1, bruto: 7.5, total: 0},
{quantity: 1, bruto: 7.5, total: 0},
{quantity: 1, bruto: 7.5, total: 0},
];
$scope.calculate = function(index) {
$scope.valuesArray[index].total = $scope.valuesArray[index].quantity * $scope.valuesArray[index].bruto;
}
关于javascript - 表格单元格上的 ng-change 更新所有单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40555255/