我对 Angular 还很陌生,所以请耐心等待。我正在尝试计算主要的“总预算”值减去显示的其他值的总和。
我的index.html当前是:
<table class="table">
<thead>
<tr>
<th>Destination</th>
<th>Total Budget</th>
<th>Hotel Cost</th>
<th>Airfare Cost</th>
<th>Miscellaneous</th>
<th>Budget Remaining</th>
<th> </th>
</tr>
</thead>
<tbody>
<tr>
<td><input class="form-control" ng-model="trip.destination"></td>
<td><input class="form-control" ng-model="trip.budget"></td>
<td><input class="form-control" ng-model="trip.lodgingCost"></td>
<td><input class="form-control" ng-model="trip.airfareCost"></td>
<td><input class="form-control" ng-model="trip.miscCost"></td>
<td><button class="btn btn-primary" ng-click="addTrip()">Add Trip</button></td>
<td><button class="btn btn-info" ng-click="update()">Update</button> <button class="btn btn-info" ng-click="deselect()">Clear</button></td>
</tr>
<tr ng-repeat="trip in trips">
<td>{{trip.destination}}</td>
<td>{{trip.budget}}</td>
<td>{{trip.lodgingCost}}</td>
<td>{{trip.airfareCost}}</td>
<td>{{trip.miscCost}}</td>
<td>{{ getRemaining() }}</td> <<!--here is where I run the calculation -->
</tr>
</tbody>
</table>
在我的controller.js中,我尝试了在stackoverflow上找到的一些内容的变体,例如this , this ,和 this ,但我大多都是未定义和 NaN,就好像实际值没有被正确读取一样?
任何帮助将不胜感激。
最佳答案
您可以在没有 Controller 功能帮助的情况下尝试它,因为它是基本计算。虽然不推荐使用此方法,但它非常适合您入门。
您可以尝试替换 <td>{{ getRemaining() }}</td>
与此:
<td>{{ trip.budget - (trip.lodgingCost + trip.airfareCost + trip.miscCost) }}</td>
这是一个简单的算术计算,如果该表达式中的所有内容都是数字,它将为您提供所需的结果。如果该表达式中的任何一项是 NaN
,结果将是 NaN
。所以你需要注意这一点。
更新:
根据评论,数据格式错误。您期望进行算术计算的数字,但它们实际上是字符串。所以像这样的计算
"1500" - ("700" + "500" + "200")
会产生一个很大的负数,如 -700498700
因为算术是在字符串连接之后完成的,即实际操作是 1500 - 700500200
结果是 -700498700
.
为了让你的 UI 正常工作,你可以尝试一个技巧。将表达式更改为:
<td>{{ (+trip.budget) - ((+trip.lodgingCost) + (+trip.airfareCost) + (+trip.miscCost)) }}</td>
这将手动将字符串类型转换为数字。但实际的修复应该在 MongoDB 上完成,以便它返回数字。
关于javascript - 如何在 AngularJS 中使用 ng-repeat 数据进行计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45180944/