2013-05-11 15 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呼び出しを通じてwholely通過する必要があるエンティティの一部である場合に有用です。

関連する問題