首页 > 解决方案 > angularjs中列值的总和

问题描述

我想计算 anagularjs 中的值的总和。

1)如果我在文本框中输入 2,它应该乘以 2000,结果将是4000

2)在第二行 id 我输入 3 它应该乘以 100 并且结果将是300

2)与第三行 id 相同,我输入 4 它应该乘以 50,结果将是200

3) 所以4000+300+200 = 4500结果应该排在总位置。

乘法工作正常。但是这里如何计算总量。如果我是4500的值,这是否可以用“四千五百”之类的词来显示数量

<table>
  <tr>
    <th colspan="3">Details of Cash</th>
  </tr>
  <tr>
    <td>Cash Notes</td>
    <td>Amount in Rs.</td>
  </tr>
  <tr>
    <td><input type="text" ng-model="amount" id="textBox2">X 2000</td>
    <td>{{ (+amount) * 2000}}</td>
    
  </tr>
  <tr>
    <td><input type="text" ng-model="amount3" id="textBox2">X 100</td>
    <td>{{ (+amount3) * 100}}</td>
    
  </tr>
  <tr>
    <td><input type="text" ng-model="amount4" id="textBox2">X 50</td>
    <td>{{ (+amount4) * 50}}</td>
    
  </tr>
  
  <tr>
    <td>Total</td>
    <td>{{total}}</td>
    
  </tr>
</table>

标签: angularjs

解决方案


在变量上添加某种观察器,并在它们发生变化时重新计算总数。我会用ng-change这个。然后只需为此调用一个通用函数。这是一个演示:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.calcTotal = function() {
    $scope.total = ($scope.amount || 0) * 2000 + ($scope.amount3 || 0) * 100 + ($scope.amount4 || 0) * 50;
  }
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

  <div ng-app="myApp" ng-controller="myCtrl">

    <table>
      <tr>
        <th colspan="3">Details of Cash</th>
      </tr>
      <tr>
        <td>Cash Notes</td>
        <td>Amount in Rs.</td>
      </tr>
      <tr>
        <td><input type="text" ng-change="calcTotal()" ng-model="amount" id="textBox2">X 2000</td>
        <td>{{ (+amount) * 2000}}</td>
      </tr>
      <tr>
        <td><input type="text" ng-change="calcTotal()" ng-model="amount3" id="textBox2">X 100</td>
        <td>{{ (+amount3) * 100}}</td>
      </tr>
      <tr>
        <td><input type="text" ng-change="calcTotal()" ng-model="amount4" id="textBox2">X 50</td>
        <td>{{ (+amount4) * 50}}</td>
      </tr>
      <tr>
        <td>Total</td>
        <td>{{total}}</td>
      </tr>
    </table>

  </div>

</body>

</html>


推荐阅读