7

I have a problem adding a number from a textbox and place it on another textbox. My situation is like this:

I have one textbox:

<input type="text" ng-model="num1" />

And whatever the input is on this textbox, this will be the value of another textbox like this:

<input type="text" value="{{ num1 + 1 }}" />

This setup shows successfully but with errors. When I type 2013 on the first, the second shows 20131 instead of 2014. I also tried using filters like this:

<input type="text" value="{{ num1 + 1 | number}}" />

but unfortunately, it doesn't work. What did I miss?

4 Answers 4

13

The value of a textbox is a string. You need to convert it to an integer/float you can do that using parseInt or parseFloat if you have decimals. By default you don't have the parseInt method available in your expression, but you can add it to the scope in your controller to make it available:

$scope.parseInt = parseInt;


<input type="text" value="{{ parseInt(num1) + 1 }}" />

You can see this in action here

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

6 Comments

No problem, just don't do too much maths in those expressions or it will get messy. There is usually a reason behind why simple things are more complicated in angular.
A better (in terms of readability, brevity, and performance) option than using parseInt would (IMHO) be to convert the input using the - operator: (num1 - 0) + 1
Wow... works like a charm. @GoloRoden your solution is super awesome.
You must not have an ng-model directive on the input field.
@azium The reason (str - 0) works is because - is a mathematical operator only, so it has to convert the sides to numbers. +(str) doesn't work, because + is both mathematical and concatenation operator, meaning its valid for both numbers and strings.
|
7

You can also use input type=number instead of text. This also has the added benefit of providing a type that matches what you expect to get.

1 Comment

Would be nice to be able to do this with select elements.
0

num1 is being interpreted as a string.

Use parseInt() or parseDouble() to convert this to a number when initializing it.

Comments

0

I found a tick method to solve. My case is that I need to parseInt something like item.qty. But I found <div ng-click="item.qty = parseInt(item.qty) + 1>Add</div> won't work.

Finally, I found this method can solve

<div ng-click = "item.qty = item.qty - 1 + 2">Add</div>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.