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?
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()" />
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With