Change model value based on other values?

I have a model with several values โ€‹โ€‹mapped to input fields. I would like to update other attributes of this model when 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 the field of hours or rates. How can i do this?

+6
source share
3 answers

Create clock expressions for variables. The natural place for this is 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 for 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()" /> 
+10
source

Alternatively, you can define price as a calculation either in the markup or on your property. The advantage of this is that it does not require any hours and, presumably, if you send them to the server server, you should probably recount it, given that the user can manipulate this before sending.

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> 
+5
source

And as an alternative, you can use ng-change (example in angular 1.5 component):

Controller:

 self.setPrice = function() { self.project.price = self.project.hours * self.project.rate; }; 

Markup:

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

This is useful when the computed value is part of an object that needs to be passed in whole through a REST call.

+1
source

Source: https://habr.com/ru/post/944789/


All Articles