Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angularjs

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?

like image 370
Melvin Avatar asked Jul 03 '13 09:07

Melvin


2 Answers

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

like image 139
Derek Ekins Avatar answered Nov 11 '22 18:11

Derek Ekins


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.

like image 34
Derokorian Avatar answered Nov 11 '22 18:11

Derokorian