Melvin
Melvin

Reputation: 6008

AngularJS how to add numbers inside the expression from a textbox?

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?

Upvotes: 7

Views: 13082

Answers (4)

Kenneth Chan
Kenneth Chan

Reputation: 530

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>

Upvotes: 0

Derokorian
Derokorian

Reputation: 1440

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.

Upvotes: 7

Derek Ekins
Derek Ekins

Reputation: 11391

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

Upvotes: 13

Amani
Amani

Reputation: 525

num1 is being interpreted as a string.

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

Upvotes: 0

Related Questions