根据其他值更改模型值?

时间:2013-05-11 21:14:22

标签: angularjs

我有一个模型,其中包含几个与输入字段关联的值。我想在其中一些属性发生变化时更新该模型的其他属性。这是一个例子:

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

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

3 个答案:

答案 0 :(得分:11)

在变量上创建监视表达式。这样做的一个自然的地方是控制器 - 类似于:

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

答案 1 :(得分:6)

或者,您可以将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>

答案 2 :(得分:1)

另外,您可以使用ng-change(角度为1.5的组件中的示例):

控制器:

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调用全部传递的实体的一部分时,这很有用。

相关问题