Reputation: 787
I am using AngularJS in one of our application.
In the code below, while loading the page the expression addition (number, valuetoadd) parses correctly and give output as 1+1=2
but while changing the input it doesn't parse correctly and it gives output as `1+2=12'.
Where do I need to change?
<div ng-controller='MathsController'>
<input type="range" min="0" max="100" step="1" value="1" ng-model='valuetoadd'/>
<p>Addition table of <b>{{valuetoadd}}</b></p>
<div ng-repeat='number in numbers'>
{{number}} + {{valuetoadd}} = {{ addition(number,valuetoadd) }}
</div>
</div>
<script type="text/javascript">
function MathsController($scope)
{
$scope.valuetoadd= 1;
$scope.numbers =[1,2,3,4,5,6,7,8,9,10];
$scope.addition = function(number,valuetoadd)
{
return number+valuetoadd;
}
}
</script>
Upvotes: 0
Views: 10296
Reputation: 2319
Another quick fix is to multiply value by 1 before addition. This will force JavaScript to convert value from string to integer.
Example:
{{value*1 + 10}}
Upvotes: 3
Reputation: 1842
You need to coerce the variables into some sort of numeric type (values from HTML inputs are passed as string by default)
$scope.addition = function (number, multiplier) {
return number + parseInt(multiplier, 10);
}
Upvotes: 2
Reputation: 36030
May be number
beging passed as a string.
Try:
$scope.addition = function(number, multiplier)
{
return + number + multiplier;
}
+
would convert the string into number.
EDIT:
Now, I see that multiplier
is passed as string.
So IT has to be converted instead...
Sorry that I did not read the code carefully.
$scope.addition = function(number, multiplier)
{
return number + +multiplier;
}
Thank you @Artur for pointing this out.
Upvotes: 3
Reputation: 4743
Seems like the root of the problem lies here: https://github.com/angular/angular.js/issues/1189
Also read this SO topic: Two-way binding with range and number input in AngularJS
As a workaround you can use the solutions proposed by thefrontender and tosh shimayama.
It's worth noticing, though, that it is the multiplier who requires parsing to integer, not the number
. See my comment to your question.
Upvotes: 3