mpora mpora - 1 year ago 67
AngularJS Question

angular js adding two numbers issue

I have this code using angular js:

<!DOCTYPE html >
<title>Untitled Page</title>
<script type="text/javascript" src=""></script>
<script type="text/javascript">
function TodoCtrl($scope) {
$ = function () {
return $scope.x + $scope.y;

<div ng-app>

<div ng-controller="TodoCtrl">
<li>Number 1: <input type="text" ng-model="x" /> </li>
<li>Number 2: <input type="text" ng-model="y" /> </li>
<li>Total <input type="text" value="{{total()}}"/></li>


I am able to do multiplication, division and subtraction but for addition, the code just concatenates the x and y values (i.e. if x = 3 and y = 4, the total is 34 instead of being 7)

What am I doing wrong?

Answer Source

If that is indeed the case then what is happening is the values that are being passed in for x and y are being treated as strings and concatenated. What you should do is convert them to numbers using parseInt

return parseInt($scope.x) + parseInt($scope.y);

or if you prefer brevity

return $scope.x*1 + $scope.y*1;