javascript - 如何在 AngularJS 中使用 ng-repeat 数据进行计算

标签 javascript angularjs angularjs-scope

我对 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>&nbsp;</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>&nbsp;&nbsp;<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/

相关文章:

javascript - 在 Javascript 中返回两个值 - return [foo, bar] vs return foo + ""+ bar

javascript - 如何在MongoDB中存储和区分数据?

javascript - 比 lodash 链更好、更高效

javascript - AngularJS/JavaScript 从另一个对象创建新对象

javascript - 如果没有互联网连接,我想 toast ,不知道该怎么做

javascript - 通过 Angular JS 处理 APlayer - 动态播放音乐

javascript - image.onLoad——在触发之前我应该​​如何保持数据可用?

javascript - Angular : switch HTML depending on screen resolution

javascript - 使用 controllerAs 时访问指令中的父范围

javascript - 指令 : toggle its boolean attribute value 的 onDblclick