2016-09-17 53 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