基于其他值更改模型值?

问题描述:

我有一个与输入字段绑定的几个值的模型。我想更新该模型的其他属性,只要其中一些属性发生变化。这里是一个例子:基于其他值更改模型值?

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

我想更新价格属性,只要在小时或费率字段发生变化。我怎样才能做到这一点?

在变量上创建监视表达式。一个自然的地方做,这是在控制器 - 有点像:

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()" /> 

或者,你可以定义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.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呼叫全部脱下传递的实体的一部分。