user6579134 user6579134 - 3 months ago 7
AngularJS Question

calculation in angularjs output fails with ng-model

I'm working on an angular project where i perform calculations on the page. In the textfield where i put the final results, when i get it an

ng-model
that answer fails to load. When i take out the
ng-model
, the answer appears.
But i want it working while it have an ng-model="total" because i will send the total value to the database. With the below script, it works

<input name="price" type="text" id="price" ng-model="price">
<input name="quantity" type="text" id="quantity"ng-model="price">
<input name="total" type="text" id="total" value="{{.price*quantity}}">


But with this

<input name="price" type="text" id="price" ng-model="price">
<input name="quantity" type="text" id="quantity"ng-model="price">
<input name="total" type="text" id="total" value="{{.price*quantity}}" ng-model="total">


it fails to works. The answer doesn't appear in the textbox

Answer

Try this instead:

<input name="price" 
       type="text"
       ng-model="price" string-to-number>

<input name="quantity" 
       type="text"
       ng-model="quantity" string-to-number>

<span>{{ price * quantity }}</span>

I'm not sure why you're trying to put the calculated value into the 3rd input, but if you are, you'll want to use ng-model-options to tell the total ngModel that it's to treat that value as a getter/setter - https://docs.angularjs.org/api/ng/directive/ngModelOptions

Also note the string-to-number directive. You're dealing with strings in the input. So in order for interpolation to work, you may need to add those.

edit

here is a working example of how I think you were trying to allow an override on the calculated value. You can enter another value in the total input and hit enter to see it working. This uses the ng-model-options - http://codepen.io/jusopi/pen/XKQzzv

Comments