Angularjs 是否基于其他值更改模型值?

Angularjs 是否基于其他值更改模型值?,angularjs,Angularjs,我有一个模型,其中有几个值与输入字段相关联。每当这些属性中的某些属性发生更改时,我想更新该模型的其他属性。以下是一个例子: <input type='number' name='hours' ng-model='project.hours' /> <input type='number' name='rate' ng-model='project.rate' /> <span>{{ project.price }} {{project.price}} 每

我有一个模型,其中有几个值与输入字段相关联。每当这些属性中的某些属性发生更改时,我想更新该模型的其他属性。以下是一个例子:

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

{{project.price}}

每当小时或费率字段发生更改时,我都希望更新price属性。如何实现这一点?

在变量上创建监视表达式。执行此操作的自然位置是在控制器中-类似于:

var updatePrice=function(){
//您可能必须对作用域变量执行空检查
$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()" />
$scope.updatePrice=updatePrice;

或者,您可以将
价格定义为标记中或对象上的计算。这样做的好处是,它不需要任何手表,如果您将手表提交到后端服务器,您可能需要重新计算手表,因为用户可以在提交之前对手表进行操作

演示:

控制器:

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


{{project.price()}}或{{project.hours*project.rate}

或者,您可以使用(例如,角度为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>

{{$ctrl.project.price}
当计算值是需要通过REST调用全部传递的实体的一部分时,这非常有用

<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>