2013-05-11 107 views
6

我有一個與輸入字段綁定的幾個值的模型。我想更新該模型的其他屬性,只要其中一些屬性發生變化。這裏是一個例子:基於其他值更改模型值?

<input type='number' name='hours' ng-model='project.hours' /> 
<input type='number' name='rate' ng-model='project.rate' /> 
<span>{{ project.price }} 

我想更新價格屬性,只要在小時或費率字段發生變化。我怎樣才能做到這一點?

回答

10

在變量上創建監視表達式。一個自然的地方做,這是在控制器 - 有點像:

var updatePrice = function(){ 
    //you might have to do null checks on the scope variables 
    $scope.project.price = $scope.project.hours * $scope.project.rate; 
} 
$scope.$watch('project.hours',updatePrice); 
$scope.$watch('project.rate',updatePrice); 

另一種可能性是使用上的輸入字段的ngChange指令:

$scope.updatePrice = updatePrice; 

<input type='number' name='hours' ng-model='project.hours' ng-change="updatePrice()" /> 
<input type='number' name='rate' ng-model='project.rate' ng-change="updatePrice()" /> 
5

或者,你可以定義price作爲計算無論是在標記中還是在對象上。這樣做的好處是它不需要任何監視,假設您將這些提交到後端服務器,您可能應該重新計算它,因爲用戶可能會在提交之前操作它。

演示:http://plnkr.co/edit/wyiKlybVh94Fr3BDiYiZ?p=preview

控制器:

$scope.project = { 
    hours: 100, 
    rate: 25, 
    price: function() { 
    return this.hours * this.rate; 
    } 
}; 

然後:

<input type='number' name='hours' ng-model='project.hours' /> 
<input type='number' name='rate' ng-model='project.rate' /> 
<span>{{ project.price() }} OR {{project.hours * project.rate}} </span> 
1

並且或者可以(在角1.5組分例如)使用ng-change

控制器:

self.setPrice = function() { 
    self.project.price = self.project.hours * self.project.rate; 
}; 

標記:

<input type="number" name="hours" ng-model="$ctrl.project.hours" ng-change="$ctrl.setPrice()"> 
<input type="number" name="rate" ng-model="$ctrl.project.rate" ng-change="$ctrl.setPrice()"> 
<span>{{ $ctrl.project.price }}</span> 

這是有用的,當所計算出的值是需要被通過一個REST呼叫全部脫下傳遞的實體的一部分。