lauw0203 lauw0203 - 1 year ago 51
Javascript Question

Storing AngularJS expression result in input

As you can see from below, I am calculating an expression,

{{ annualIncome * 4.5 }}
, in one input, and recalculating the same expression in another input, instead of storing the result of the expression and passing it to the other input as I am unsure of how to do that.

Example:

%label Equity Loan ({{ selectedLocation.loan }}%):
%input#equity_loan{ "disabled" => "disabled", "value" => "{{ selectedLocation.mortgage === 55 ? ((annualIncome * 4.5) / 11) * 9 : ((annualIncome * 4.5) / 15) * 4 }}" }

%label Mortgage ({{ selectedLocation.mortgage }}%):
%input#mortgage{ "disabled" => "disabled", "value" => "{{ annualIncome * 4.5 }}" }


I have tried ng-model, but it doesn't seem to work.

Also, I have tried to change the values to a currency by adding "| currency" onto the end of my expression, which also didn't work, but I'm guessing it might be because I need to convert each expression result?

Answer Source

Well, you can't use variables in angular expressions, but you could do it in your controller after the annual income variable is changed; which is bound to in your view using the "ng-model" => "annualIncome" statement.

In order to calculate values after changing a value, you could set up a watch in your scope. The function will be called each time the value is updated. If you want to add a delay and not calculate it immediately you can use the debounce options in ng-model-options; example:

%input{"ng-model-options" => "{debounce: { 'default': 500, 'blur': 0 }}"}

Then it's simply a way of structuring your code using variables.

$scope.$watch('annualIncome', function(value, oldValue) {
  var annualIncome = value; // same as $scope.annualIncome
  var parts = selectedLocation.mortgage === 55 ? 11 : 15;
  var factor = selectedLocation.mortgage === 55 ? 9 : 4;
  var annualValue = annualIncome * 4.5;
  $scope.result = {
    propertyValue: annualValue + (annualValue / parts) + ((annualValue / parts) * factor),
    deposit: annualValue / parts
    // and so on..
  };
});

Since the result variable is set on the scope, you can bind to it in your view using property binding.

%input#property_value{ "disabled" => "disabled", "value" => "{{ result.propertyValue }}" }