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

时间:2017-07-19 04:24:53

标签: 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上发现的一些内容的变体,例如thisthisthis,但我主要是一直未定义和NaN,好像实际值没有被正确读取?

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

您可以在没有控制器功能的帮助下尝试它,因为它是基本计算。虽然不建议采用这种方法,但它很适合您入门。

您可以尝试将<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上完成,以便返回数字。

答案 1 :(得分:0)

将trip对象作为参数传递给getRemaining()函数。

<td>{{ getRemaining(trip) }}</td>

在控制器中,使用此对象获取计算值而不是$ scope.trip。所以你的功能就是,

$scope.getRemaining = function(trip){ 
    var remainder = trip.budget - ( trip.airfareCost + trip.lodgingCost + trip.miscCost); 
    return remainder; 
}