简体   繁体   中英

Angular JS - Instead of sum values are getting concatenated

I'm new to AngularJS, just created a simple form in order to understand. I tried multiplying 2 input values, I'm good here, but when I use same code to sum those 2 input values it is getting concatenated instead of sum.

My code:

<div ng-app ng-init="fval = 1;sval = 2">
<div>
    First Value:
</div>
<div>
    <input type="text" ng-model="fval" />
</div>
<br />
<div>
    Second Value:
</div>
<div>
    <input type="text" ng-model="sval" />
</div>
<br />
<div>
    <label id="lblResult">{{fval * sval}}</label>
</div>

Here I have given hardcoded values for my inputs, initially we will get result as 6. Also when we change the inputs we will get correct result for multiplying 2 values.

I changed my code for addtion as below:

<label id="lblResult">{{fval + sval}}</label>

After running the application I got the correct value as 3 , but when I change my input values I'm getting concatenated values. Like if I change my text box values, for firstTextBox = 12 & secondTextBox = 3, then I'm getting result value as '123'.

Hence, I'm landing with correct value when I run the application first time, but changing inputs on client side is concatenating.

Sorry for my English, since it is not my first language. Can anyone please help me where I'm going wrong.

Try Changing

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

To

<input type="number" ng-model="fval" />

That happens because the type of the ng-model is declared as text.

<input type="text" ng-model="fval" />
<input type="text" ng-model="sval" />

So when you add them using {{fval + sval}} you get a string since the sum of two string is the result of concationation of these two strings.
In order for them to work as expected you should replace them like below:

<input type="number" ng-model="fval" />
<input type="number" ng-model="sval" />

Hope this saves your time.

This is just a JavaScript thing. Your numbers are strings, and + is the concatenation operator. One way to solve this:

parseInt(fval) + parseInt(sval)

Edit: This is not allowed within Angular expressions (see below). Answer is valid for use in 'normal' JS code though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM