GSto GSto - 2 months ago 6
AngularJS Question

Change Model value based on other values?

I have a model with several values that are tied to input fields. I would like to update other attributes of that model whenever some of these attributes change. here is an example:

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


I would like to update the price attribute whenever there is a change in either the hours or rates field. How can I accomplish this?

Answer

Create watch expressions on the variables. A natural place to do this is in the controller - something like:

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

Another possibility is to use the ngChange directive on the input fields:

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