如何获得Angularjs中的输入字段总和以及需要赋值给变量的总和?

时间:2017-03-01 06:19:28

标签: html angularjs

enter image description here

这里我有一个动态生成的表行,在这里我必须计算每行的输入总和并需要分配给一个变量。现在在HTML中我能够求和,但我需要将一些变量分配给API。

这是我的HTML代码:

$scope.productids = ['111', '222', '333', '444', '5555'];
$scope.targets = [{
  'pid': '',
  'week1': '',
  'week2': '',
  'week3': '',
  'week4': '',
  'total': ''
}];
$scope.addNewChoice = function() {
  $scope.targets.push({
    'pid': '',
    'week1': '',
    'week2': '',
    'week3': '',
    'week4': '',
    'total': ''
  });
};

$scope.removeChoice = function(val) {
  console.log("index------>", val);
  $scope.targets.splice(val, 1);
};
thead th {
  background: rgba(13, 3, 3, 0.05);
  color: black;
  font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<table class="table table-bordered">
  <thead>
    <tr>
      <th>Product Id</th>
      <th>week1</th>
      <th>week2</th>
      <th>week3</th>
      <th>week4</th>
      <th>Total</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody>
    <tr data-ng-repeat="target in targets">
      <td align="center">
        <select class="form-control" style="width: 170px;border: 1px solid skyblue;" data-ng-model="target.pid" ng-change="getUnitsofProduct(target.pid)">
           <option value="">Select pid</option>
           <option data-ng-repeat="pid in productids">{{pid}}</option>
        </select>
      </td>
      <td align="center">
        <input class="form-control" style="width: 70px" type="text" name="" ng-model="target.week1"> {{units}}
      </td>
      <td align="center">
        <input class="form-control" style="width: 70px" type="text" name="" ng-model="target.week2">
      </td>
      <td align="center">
        <input class="form-control" style="width: 70px" type="text" name="" ng-model="target.week3">
      </td>
      <td align="center">
        <input class="form-control" style="width: 70px" type="text" name="" ng-model="target.week4">
      </td>
      <td align="center">
         {{ (target.week1 * 1) + (target.week2 * 1)+ (target.week3 * 1)+ (target.week4 *1) }}
      </td>
      <td>
        <button class="add" style="background-color: #008CBA;" data-ng-show="$last" data-ng-click="addNewChoice()">+</button>
        <button class="add" data-ng-click="removeChoice($index)" style="background-color:#f44336;margin:0px;">-</button>
      </td>
    </tr>
  </tbody>
</table>

2 个答案:

答案 0 :(得分:0)

您可以对此总字段使用ng-bind:

<td><span ng-bind="target.week1+target.week2+target.week3+target.week4"><span></td>

答案 1 :(得分:0)

您可以使用输入隐藏字段ng-model =&#34; target.total&#34; :

<input class="form-control" style="width: 70px" type="hidden" name="" ng-model="target.total">

{{ target.total = (target.week1 * 1) + (target.week2 * 1)+ (target.week3 * 1)+ (target.week4 *1) }