Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Model value based on other values?

Tags:

angularjs

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?

like image 619
GSto Avatar asked May 11 '13 21:05

GSto


2 Answers

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()" />
like image 184
joakimbl Avatar answered Sep 22 '22 18:09

joakimbl


Alternatively, you could define price as a calculation either in the markup or on your object. The benefit to this is it doesn't require any watches and presumably if you do submit these to a backend server you probably should be recalculating it considering the user could manipulate that prior to submit.

Demo: http://plnkr.co/edit/wyiKlybVh94Fr3BDiYiZ?p=preview

Controller:

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

Then:

<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>
like image 45
lucuma Avatar answered Sep 18 '22 18:09

lucuma