AngularJS how to add numbers inside an expression from a text field?

I have a problem adding a number from a text box and placing it in another text box. My situation is this:

I have one text box:

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

And regardless of what is entered in this text field, it will be the value of another text field like this:

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

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

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

but unfortunately it does not work. What did I miss?

+6
source share
4 answers

The value of the text field is a string. You need to convert it to an integer / float, which you can do using parseInt or parseFloat if you have decimal numbers. By default, you do not have the parseInt method available in your expression, but you can add it to your controller scope to make it available:

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

You can see it in action here.

+13
source

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

+5
source

num1 is interpreted as a string.

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

0
source

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

Finally, I found that this method can solve

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

Source: https://habr.com/ru/post/948612/


All Articles