1

I'm trying to calculate 2 values that the user typed in and set that result as the ng-model for another value. However I can't seem to get this code to work.

<input type="number" ng-model="a">
<input type="number" ng-model="b">
<input type="number" ng-init="c = a * b" ng-model="c">

I have also tried using parseFloat:

//in controller
$scope.parseFloat = parseFloat();

<input type="number" ng-init="c = (parseFloat(a) * parseFloat(b))" ng-model="c">

I CAN get the result I want as a label {{a * b | number:2 | currency}}, but not as an ng-model. Any ideas?

JoshPMP
  • 31
  • 2
  • 7
  • Possible duplicate of http://stackoverflow.com/questions/30579223/ng-init-not-working-when-the-ng-options-list-is-changed#answer-30579456 – PSL Jun 05 '15 at 14:03
  • ng-init can be used only with ng-repeat directive. you should use c as ng-model and update the value on on-change event – fantarama Jun 05 '15 at 14:04
  • @fantarama to be precise, ng-init _can_ be used anywhere, but appropriate usage is for aliasing special properties of ng-repeat. – PSL Jun 05 '15 at 14:06
  • @PSL i agree, but since documentation strongly discourage usage outside ng-repeat scope I don't consider a valid solution using it for other purpose – fantarama Jun 05 '15 at 14:10
  • @fantarama yup... i agree 101%, in fact i had mentioned it elaborately in the linked answer as well. I only commented when you said `can be used only`. :) – PSL Jun 05 '15 at 14:11
  • I should've pointed out that this IS inside of an ng-repeat. – JoshPMP Jun 05 '15 at 14:25

1 Answers1

1

ng-init is only called once, when the node is intialized. You can try to use ng-change on the two inputs to set value of c

<input type="number" ng-model="a" ng-change='c=a*b'>
<input type="number" ng-model="b" ng-change='c=a*b'>
Chandermani
  • 42,589
  • 12
  • 85
  • 88
  • This would make sense to me but is still not working. I'm actually getting a NAN error even though I have type="number". Any ideas on that? – JoshPMP Jun 05 '15 at 14:29