2016-09-17 55 views
0

您好我有一个JSON像这样Angularjs动态文本字段和乘两个领域

[ 
    { 
    "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> 

现在我想计算出总的(数量*价格)每增加一个选择,每当他们把数量和速率,并把它在总领域请帮助

+0

你应该做的事'{{}}'而不是'<% %>' –

+0

我想你应该能够inititate一个作为“qty”和“rate”的乘积,如'ng-init =“calculatedTotal = choice.rate * choice.qty”',然后将其分配给'ng-model =“calculatedTotal”',总计为 –

+0

'ng-init'只会在构造视图时运行一次 - 当'rate'或'qty'改变时它不会更新。 – Lex

回答

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)"> 
+0

谢谢我做过这样的事情之前我做错了$ scope.choice.total = choice.qty * choice.rate;而不是choice.total = choice.qty * choice.rate; – sanu