Angularjs动态文本字段并乘以两个字段

时间:2016-09-17 14:50:01

标签: angularjs dynamicform

嗨,我有一个Json喜欢这个

[
  {
    "id": 1,
    "name": "Furniture & Fixture",
    "choices": [
      {
        "req_goods": "",
        "qty": "10",
        "rate": "",
        "total": ""
      }
    ]
  },
  {
    "id": 2,
    "name": "Miscellaneous Property",
    "choices": [
      {
        "req_goods": "",
        "qty": "",
        "rate": "",
        "total": ""
      }
    ]
  },
  {
    "id": 3,
    "name": "Office Equipment",
    "choices": [
      {
        "req_goods": "",
        "qty": "",
        "rate": "",
        "total": ""
      }
    ]
  }
]

这里的选择是我的动态字段用户可以根据需要添加尽可能多的选择,我的添加/删除js就是这样

$scope.addNewChoice = function(id){
        $scope.capital_budgets[id].choices.push({});
    };
    $scope.removeChoice = function(parent_id,id) {      
        $scope.capital_budgets[parent_id].choices.splice(id,1);
      };

我的HTML

<div ng-repeat="cb in capital_budgets">
  <div><b><% $index+1 %> <% cb.name %></b></div>                  

  <div ng-repeat="choice in cb.choices">    
    <input type="text" ng-model="choice.req_goods">                 
    <input type="text" ng-model="choice.qty">
    <input type="text" ng-model="choice.rate">
    <input type="text" ng-model="choice.total">

   <button type="button" ng-hide="$first" ng-click="removeChoice($parent.$index,$index)">-</button>

  </div>
  <button type="button" ng-click="addNewChoice($index)">+</button>

</div>

现在我想计算每个添加的选项的总数(数量*率),只要他们把数量和费率放在总数字段中请帮助

1 个答案:

答案 0 :(得分:2)

实现此目的的一种方法是在控制器中创建一个方法来进行计算,然后只需更改qtyrate即可调用它。

控制器:

$scope.updateTotal = function(choice) {
    if(!choice.qty || !choice.rate) {
        choice.total = 0;
    } else {
        choice.total = choice.qty * choice.rate;
    }
};

HTML:

<input type="text" ng-model="choice.qty" ng-change="updateTotal(choice)">
<input type="text" ng-model="choice.rate" ng-change="updateTotal(choice)">