2

I'm doing some simple data binding like so:

<input type="text" class="form-control" model="amount">
<label>Your amount is {{amount * 10 }}</label>

However, initially, when the text input is empty it returns NaN.

How can I prevent this from happening with Angular?

1
  • You have to watch and convert the datatype of amount to integer otherwise its string multiplying with 10 which will give you unexpected results. Commented Sep 28, 2014 at 8:59

5 Answers 5

8

You can try this:

<input type="text" class="form-control" model="amount">
<label>Your amount is {{ (+amount) * 10 }}</label>

HTML text inputs are text by definition. the added + will convert it to an number prior to being used.

Sign up to request clarification or add additional context in comments.

Comments

1

Use ternary operator to check isNaN in your tempalte like below.

<input type="text" class="form-control" model="amount">
<label>Your amount is {{ (!isNaN(amount)) ?  (amount * 10) : '' }}</label>

Comments

1

Your amount is

{{ (amount * 10) || "0" }}

This works fine.

Comments

0

Your amount is {{ (amount * 10) || "0" }}

Comments

0
a = (a*10)+b;

where b is undefined value.so, we are getting NaN value.

a = (a*10) || b;

this || operator instead of "+" solved my issue

2 Comments

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
Please add some explanation to your answer such that others can learn from it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.